How to set setVisible for all JPanels on JFrame
How can I set the Visible value for all JPanels on a JFrame? I know that I can use JFrame.JPanel.setVisible for each panel, but I would like to do it for everyone.
This is very helpful because I don't know the witch panel is visible. So I want to hide the whole panel after the action and show 1 or 2 panels.
+3
source to share
2 answers
Here is a general method that does it. It iterates through all the components of the container hierarchy, finds those that match a specific class of components, and sets their visible property:
static void setComponentVisibility(Container container,
Class<? extends Component> componentClass, boolean visible) {
for (Component c : container.getComponents()) {
if (componentClass.isAssignableFrom(c.getClass())) {
c.setVisible(visible);
} else if (c instanceof Container) {
setComponentVisibility((Container)c, componentClass, visible);
}
}
}
Use it like this:
setComponentVisibility(frame, JPanel.class, false);
+1
source to share
Simple solution :
save all your panels as instances or list
General solution :
iterating 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());
}
+4
source to share