Arshad Ali
Arshad Ali

Reputation: 3274

could not remove/add jpanel in jframe

I'm stuck with an issue that is, I have a JFrame with 2 JPanels added in it as showed in Figure : enter image description here in figure above, one JPanel have some JButtons and second JPanel have some form fields, I want to change/(remove old and add new JPanel) when I click on JButtons in first JPanel accordingly as shown bellow : enter image description here

I have code snippet :

myPanel.clickListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {

                    MainFrame.this.getContentPane().remove(((BorderLayout)getLayout()).getLayoutComponent(BorderLayout.CENTER));
                    MainFrame.this.getContentPane().add(twoPanel, BorderLayout.CENTER);
                    MainFrame.this.invalidate();
                    MainFrame.this.validate();
                }
            });


    myPanel.clickListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    MainFrame.this.getContentPane().remove(((BorderLayout)getLayout()).getLayoutComponent(BorderLayout.CENTER));
                    MainFrame.this.getContentPane().add(customerPanel, BorderLayout.CENTER);
                    MainFrame.this.invalidate();
                    MainFrame.this.validate();
                }
            });

            MainFrame.this.setMaximumSize(new Dimension(600, 550));
            MainFrame.this.setMinimumSize(new Dimension(599, 549));
            MainFrame.this.setSize(600, 550);
            MainFrame.this.setResizable(false);
            MainFrame.this.setVisible(true);
        }
    });

through above code I'm able to add new JPanel but unable to remove first JPanel.

Upvotes: 0

Views: 366

Answers (1)

pcejrowski
pcejrowski

Reputation: 612

in my opinion you should use CardLayout. It allows you to change visibility of JPanel, so that is actually what you want to do. You define two JPanels for the right side and then in listner just toggle them.

Look here for the example: https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

Upvotes: 2

Related Questions