Reputation: 5
I am quite new to Java and am trying to set the visible property to false for all JPanels on my JFrame (frame.)
When I execute the following, It returns null to console:
public void mouseClicked(MouseEvent e){
for (Component c : frame.getComponents()) {
System.out.println(c.getName());
if (c instanceof JPanel) {
((JPanel)c).setVisible(false);
}
}
panelDispatch.setVisible(true);
panelDispatch.requestFocus();
}
What I want it to do is set all the panels visibility to false then set the selected panels visibility to true. 3 JPanels are added to frame.
What am I doing wrong here?
Any help would be greatly appreciated.
Upvotes: 0
Views: 295
Reputation: 285430
I can't tell why you're seeing null, and I'm not sure in what way you're seeing it, a NullPointerException perhaps, but I do know that you appear to be removing the JFrame's contentPane, glassPane and rootPane inadvertently, a dangerous thing to do. Instead just use a CardLayout that should allow you to easily and simply swap your GUI views as this is exactly what CardLayout was built for. Please check out the CardLayout Tutorial for more information.
Edit
For examples of CardLayout-using GUI's, please check out:
This one is unusual in that it uses a CardLayout and has one panel fading into the other panel:
Upvotes: 2
Reputation: 159854
Components are added to a ContentPane
of a JFrame
rather than the RootPane
. You're seeing null
displayed to the console as you probably havent set the name property of the component
for (Component c : getContentPane().getComponents()) {
Upvotes: 3