Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I setVisible for all JPanel's on JFrame

Tags:

java

swing

jpanel

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.

like image 251
110precent Avatar asked Dec 03 '25 22:12

110precent


1 Answers

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());
}
like image 154
Jens Piegsa Avatar answered Dec 06 '25 14:12

Jens Piegsa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!