Returns a set of all components under the given parent. - Java Swing

Java examples for Swing:JComponent

Description

Returns a set of all components under the given parent.

Demo Code

/*/*from w  w  w .j av  a 2s. com*/
 * Copyright 2008-2014, David Karnok 
 * The file is part of the Open Imperium Galactica project.
 * 
 * The code should be distributed under the LGPL license.
 * See http://www.gnu.org/licenses/lgpl.html for details.
 */
//package com.java2s;
import java.awt.Component;

import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;

import java.util.Set;

import javax.swing.JComponent;

public class Main {
    /**
     * Returns a set of all components under the given parent.
     * @param parent the parent
     * @return the set of components
     */
    public static Set<JComponent> allComponents(JComponent parent) {
        Set<JComponent> result = new HashSet<>();
        Deque<JComponent> queue = new LinkedList<>();
        queue.add(parent);
        while (!queue.isEmpty()) {
            JComponent c = queue.removeFirst();
            result.add(c);
            for (Component c0 : c.getComponents()) {
                if (c0 instanceof JComponent) {
                    queue.add((JComponent) c0);
                }
            }
        }
        result.remove(parent);
        return result;
    }
}

Related Tutorials