13

How can I get all the components of a panel in Java Swing?

Is there any method like foreach in C# to deal all the child components of a JPanel?

Roman C
  • 47,329
  • 33
  • 60
  • 147

2 Answers2

19

You may use the method getComponents:

Component[] components = jpanel.getComponents();
Howard
  • 36,183
  • 6
  • 60
  • 81
  • This will get the child components, but not those components' children. For example, if your panel has containers such as CollapsiblePanel, the set `components` will contain a reference to that CollapsiblePanel, but not its child components. – Jonathan Landrum Oct 21 '20 at 15:25
1

if you have more than one JPanel and you want to get all components Name try this:

public void getAllComponetsNameInJPanels(JPanel... panels) {
    Component[] components;
    String componentName;
    for (JPanel panel : panels) {
        components = panel.getComponents();            
        for (Component compo : components) {
            componentName = compo.getClass().getName();
            System.out.println(compo.getClass().getName().substring(componentName.indexOf("swing.") + "swing.".length(), componentName.length()));
        }
        System.out.println("=====================");
    }
}