lolhaha
lolhaha

Reputation: 109

Open another panel inside another panel after pressing button

I have been getting an error saying that i didn't add some methods(the action performed) but i already did. I'm having trouble opening the panel2.

public class panel1 extends JPanel implements ActionListener(){
    private panel2 p2=new panel2();
    private JButton button;

    public panel1(){
    button=new JButton("open panel2");
    add(button,BorderLayout.BEFORE_FIRST_LINE);
    button.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent ae) {

            add(p2);

        }

    });

  }

}

Upvotes: 2

Views: 581

Answers (2)

boycod3
boycod3

Reputation: 5317

You can check the below code for replacing jpanel without switching jframe.  



contentPanel.removeAll();
        contentPanel.repaint();
        contentPanel.revalidate();
        contentPanel.add(//add your panel here);
        contentPanel.repaint();
        contentPanel.revalidate();

Upvotes: 0

Jan
Jan

Reputation: 13858

Consider these changes:

public class panel1 extends JPanel implements ActionListener(){
    private panel2 p2=new panel2();
    private JButton button;

    public panel1(){
    button=new JButton("open panel2");
    add(button,BorderLayout.BEFORE_FIRST_LINE);
    button.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent ae) {
            //Add readability: Where to add?
            panel1.this.add(p2);
        }

    });

  }

  //THIS HERE makes your panel1 implment ActionListener
  @Override
  public void actionPerformed(ActionEvent ae) {

  }
}

Please also note commom Java naming conventions - Class names should start with uppercase letter (Panel1 extends JPanel)

Upvotes: 1

Related Questions