0

I am working with IntelIJ and what I am trying to do is:

https://i.stack.imgur.com/4MOgI.png

While hitting the Panel1Button the right JPanel should switch on the Panel1 and analogical with the Panel2Button but what happens is some small square appears.

Code:

GridBagLayout layout = new GridBagLayout();
Panel1 p1;
Panel2 p2;
private JButton panel1Button;
private JButton panel2Button;
private JPanel DynamicPanel;
private JPanel mainPanel;

public Frame1(){
    p1 = new Panel1();
    p2 = new Panel2();

    DynamicPanel.setLayout(layout);
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 0;
    DynamicPanel.add(p1);
    c.gridx = 0;
    c.gridy = 0;
    DynamicPanel.add(p2);
    p1.setVisible(false);
    p2.setVisible(false);

    panel1Button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Button1");
            p1.setVisible(true);
            p2.setVisible(false);
        }
    });
    panel2Button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Button2");
            p1.setVisible(false);
            p2.setVisible(true);
        }
    });
}

I'm also want to separate the p1 and p2 panels in different classes. Panel1 and Panel2 looks like this:

https://i.stack.imgur.com/jneQP.png

camickr
  • 321,443
  • 19
  • 166
  • 288

1 Answers1

0

While hitting the Panel1Button the right JPanel should switch on the Panel1 and analogical with the Panel2Button

Then the panel on the right should be using a CardLayout. Then you can just swap panels when you click on the button.

Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.

camickr
  • 321,443
  • 19
  • 166
  • 288