Java tutorial
//package com.java2s; import java.awt.Component; import java.awt.Container; import java.util.ArrayList; public class Main { /** * Fills up the given ArrayList with all Components, matching to the given * class file, found downwards the given Container. The Container should be * a JRootPane for example. * * @param container * Container that should be searched for The Component * @param recursive * An empty ArrayList which will be filled up or null if a new * ArrayList should be returned. * @return An array of the type specified with the className will be * returned. If className is <code>null</code> an array over * {@link Component} will be returned. */ private static ArrayList<Component> getAllComponentsRecursive(Container container, Class<? extends Component> classNames[], ArrayList<Component> recursive) { //is there no class name defined, just setup the default value. if (classNames == null || classNames.length == 0) { classNames = new Class[] { Component.class }; } // No ArrayList, just create a new one. if (recursive == null) { // recursive = new Object[0]; recursive = new ArrayList<>(100); } // No Container, nothing to do. if (container == null) { return recursive; } // Search for the component which is an instance of the Class specified // with the className parameter for (int i = 0; i < container.getComponentCount(); i++) { try { Component comp = container.getComponent(i); if (comp instanceof Container) { getAllComponentsRecursive((Container) comp, classNames, recursive); } for (int j = 0; j < classNames.length; j++) { if (classNames[j] == null || classNames[j].isInstance(comp)) { recursive.add(comp); break; } } } catch (Exception e) { // container.getComponent(i); can fail if it was removed. } } return recursive; } }