How can I determine all of the components contained in a JFrame?

Scott Stanchfield

To get a list of all components in a JFrame, you could need to write a recursive method like the following:

public void getAllComponents(Component c, Collection collection) {
  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.

If you don't have a reference to the frame, you can use
to find it (this method is defined for Swing JComponents only). For AWT components, you can use

(Note that SwingUtilities doesn't require the GUI be written in Swing...)

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact