Search all TreeNodes from JTree that use the specified obj as its UserObject. - Java Swing

Java examples for Swing:JTree

Description

Search all TreeNodes from JTree that use the specified obj as its UserObject.

Demo Code


//package com.java2s;
import java.util.ArrayList;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class Main {
    /**/*  w ww  .  java  2 s  .  com*/
     * Search all TreeNodes that use the specified obj as its UserObject.
     * @param obj
     * @param tree a JTree whose TreeNode is DefaultMutableTreeNode.
     * @return a List of DefaultMutableTreeNodes. An empty list will be returned
     * if no TreeNode is found.
     */
    public static java.util.List searchNodes(Object obj, JTree tree) {
        java.util.List nodes = new ArrayList();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree
                .getModel().getRoot();
        searchNodes(obj, root, nodes);
        return nodes;
    }

    public static void searchNodes(Object obj,
            DefaultMutableTreeNode treeNode, java.util.List nodes) {
        if (treeNode.getUserObject() == obj)
            nodes.add(treeNode);
        for (int i = 0; i < treeNode.getChildCount(); i++) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeNode
                    .getChildAt(i);
            searchNodes(obj, node, nodes);
        }
    }
}

Related Tutorials