How can I determine all of the components contained in a JFrame?
Created Aug 14, 2001
Scott Stanchfield To get a list of all components in a JFrame, you could need to write a recursive method like the following:
If you don't have a reference to the frame, you can use
public void getAllComponents(Component c, Collection collection) {
collection.add(c);
if (c instanceof Container) {
Component[] kids = ((Container)c).getComponents();
for(int i=0; i<kids.length; i++)
getAllComponents(kids[i], collection);
}
}
You would then pass in any collection you want to the method.
If you wanted to perform a different action on each component, you could replace the "collection.add(c)" call with whatever code you wish.
component.getTopLevelAncestor();to find it (this method is defined for Swing JComponents only). For AWT components, you can use
SwingUtilities.getWindowAncestor(comp);
(Note that SwingUtilities doesn't require the GUI be written in Swing...)