How to make an added JPanel
visible inside a parent JPanel
?
I am using Netbeans for designing my UI.
I have a MainFrame.java
, which contains two panels; namely headerPanel
and bodyPanel
.
In headerPanel
I have put three buttons,let it be button1
, button2
and button3
.
Also I have created three separate files extending JPanel
, name it panel1
, panel2
and panel3
.
Then I added all my three panels inside bodypanel
in MainFrame.java
in constructor.
bodyPanel.add(panel1);
bodyPanel.add(panel2);
bodyPanel.add(panel3);
I want that on clicking the respective buttons only respective panels should appear in the bodypanel
in mainframe, i.e. if I click button1
then panel1
should be displayed.
I have already tried the following code in button1
mouse listener method:
bodyPanel.validate();
bodyPanel.getComponent(0).setVisible(true);
But panel1
does not appear. I did it cause added components in a panel are allotted index. So first I tried to get the components and then make it visible. It did not work.
your requirement truely full filled by CARD LAYOUT see this example link
and below example Link
the perfect code for your problem case is
out put
Use a CardLayout, as shown here.
Use the CardLayout. Below is a Helper class that I have written. Hope it helps.