How can I setVisible for all JPanel on JFrame? I know that I can use JFrame.JPanel.setVisible for each panel, but I'd like do it ones for all.
It's very usefull because I don't know witch panel are visible. So I want hide all panel after action and show 1 or 2 panels.
Simple solution:
store all your panels as instances or in a list
Generic solution:
iterate the widget tree
private void setAllChildPanelsVisible(Container parent) {
Component[] components = parent.getComponents();
if (components.length > 0) {
for (Component component : components) {
if (component instanceof JPanel) {
((JPanel) component).setVisible(true);
}
if (component instanceof Container) {
setAllChildPanelsVisible((Container) component);
}
}
}
}
How to use it:
@Test
public void testSetAllChildPanelsVisible() {
JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
frame.getContentPane().add(panel1);
JPanel panel2 = new JPanel();
panel1.add(panel2);
panel1.setVisible(false);
panel2.setVisible(false);
assertFalse(panel1.isVisible());
assertFalse(panel2.isVisible());
setAllChildPanelsVisible(frame.getContentPane());
assertTrue(panel1.isVisible());
assertTrue(panel2.isVisible());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With