How to get all elements inside a JFrame?

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.

Leave a Comment