Adds all JTree nodes with a specific user object of a node and it's children. - Java Swing

Java examples for Swing:JTree

Description

Adds all JTree nodes with a specific user object of a node and it's children.

Demo Code


//package com.java2s;

import java.util.Collection;
import java.util.Enumeration;

import javax.swing.tree.DefaultMutableTreeNode;

public class Main {
    /**//  w  w w .ja v a  2 s . c  om
     * Adds all nodes with a specific user object of a node and it's children.
     *
     * @param foundNodes container to add found nodes
     * @param rootNode   node to search
     * @param userObject user object to compare with equals
     * @param maxCount   maximum count of nodes to add
     */
    @SuppressWarnings("unchecked")
    public static void addNodesUserWithObject(
            Collection<? super DefaultMutableTreeNode> foundNodes,
            DefaultMutableTreeNode rootNode, Object userObject, int maxCount) {
        if (foundNodes == null) {
            throw new NullPointerException("foundNodes == null");
        }
        if (rootNode == null) {
            throw new NullPointerException("rootNode == null");
        }
        if (userObject == null) {
            throw new NullPointerException("userObject == null");
        }
        if (maxCount < 0) {
            throw new IllegalArgumentException("Negative max count: "
                    + maxCount);
        }
        int foundNodeCount = foundNodes.size();
        for (Enumeration<DefaultMutableTreeNode> children = rootNode
                .children(); children.hasMoreElements()
                && (foundNodeCount <= maxCount);) {
            DefaultMutableTreeNode child = children.nextElement();
            if (userObject.equals(child.getUserObject())) {
                foundNodes.add(child);
            } else {
                // recursive
                addNodesUserWithObject(foundNodes, child, userObject,
                        maxCount);
            }
        }
    }
}

Related Tutorials