0
votes

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.

1
for why reasons is there invalidate();, use CardLayout instead thatmKorbel
Agree with @mKorbel. Use a CardLayout as shown in this answer.Andrew Thompson
1) See also Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (Yes.) 2) Please learn common Java nomenclature (naming conventions - e.g. EachWordUpperCaseClass, firstWordLowerCaseMethod(), firstWordLowerCaseAttribute unless it is a CONSTANT) and use it consistently.Andrew Thompson
CardLayout, CardLayout, CardLayoutMadProgrammer

1 Answers

2
votes

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