Gets all child components that are, or derive from, the given class. - Java java.awt

Java examples for java.awt:Component

Description

Gets all child components that are, or derive from, the given class.

Demo Code

/*//from  ww  w  . j a va2s .  c om
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2011, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
//package com.java2s;
import java.awt.Component;
import java.awt.Container;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;

public class Main {
    /**
     * Gets all child components that are, or derive from, the given class.
     * This method is adapted from the SwingUtils class written by Darryl Burke.
     * (Accessed from: http://tips4java.wordpress.com/2008/11/13/swing-utils/).
     *
     * @param <T> Swing type derived from JComponent
     * @param clazz the component class
     * @param parent the parent container
     * @param includeNested whether to recursively collect nested components
     *
     * @return list of child components
     */
    public static <T extends JComponent> List<T> getChildComponents(
            Class<T> clazz, Container parent, boolean includeNested) {

        List<T> children = new ArrayList<T>();

        for (Component c : parent.getComponents()) {
            boolean isClazz = clazz.isAssignableFrom(c.getClass());
            if (isClazz) {
                children.add(clazz.cast(c));
            }
            if (includeNested && c instanceof Container) {
                children.addAll(getChildComponents(clazz, (Container) c,
                        includeNested));
            }
        }

        return children;
    }
}

Related Tutorials