Search code examples
javaswingjcomponent

How to get all elements inside a JFrame?


I have this code to get all the elements I need and do some processing. The problem is I need to specify every panel I have to get the elements inside it.

for (Component c : panCrawling.getComponents()) {
    //processing
}
for (Component c : panFile.getComponents()) {
    //processing
}
for (Component c : panThread.getComponents()) {
    //processing
}
for (Component c : panLog.getComponents()) {
    //processing
}
//continue to all panels

I want to do something like this and get all the elements without need specefy all the panels names. How I do this. The code below don't get all the elements.

for (Component c : this.getComponents()) {
    //processing
}

Solution

  • You can write a recursive method and recurse on every container:

    This site provides some sample code:

    public static List<Component> getAllComponents(final Container c) {
        Component[] comps = c.getComponents();
        List<Component> compList = new ArrayList<Component>();
        for (Component comp : comps) {
            compList.add(comp);
            if (comp instanceof Container)
                compList.addAll(getAllComponents((Container) comp));
        }
        return compList;
    }
    

    If you only want the components of the immediate sub-components, you could limit the recursion depth to 2.