How to get children of a JComponent

Portrait de dash


Sometimes, you are led to make some operations on all the JButtons, JMenus, etc. contained in a JFrame.
You may have to output a listing of the controls or output a file showing the state of a Swing window.

In those cases, you will be trying to enumerate all Swing components (JComponent) in your frame.

To make such a thing, it is quite simple, and it won't change whether you code in .NET or Java (I already used this technique in a .NET form, to show a list of fields which contents would be irrelevant) :

  1. First, make sure the component to check is valid (neither null, nor any incorrect state)
  2. Write a recursive method, that takes a JComponent and a object of type Vector<JComponent> in which you list all components.
  3. This method adds the component passed as a parameter, and calls itself for all components that are direct children of the component

When run, this code displays the name of all components in a FrameView :

    public void showCompChildren (JComponent comp) {
    System.out.println (comp.getName());
    for (int ind=0; ind<comp.getComponentCount(); ind++) {

    public DesktopApplication1View(SingleFrameApplication app) {




Not that difficult, is it ?


A Netbeans 6 project with the code

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Les lignes et les paragraphes vont à la ligne automatiquement.

Plus d'informations sur les options de formatage

Enter the characters shown in the image.