Search a JTree DefaultMutableTreeNode whose userObject is the specified obj. - Java Swing

Java examples for Swing:JTree

Description

Search a JTree DefaultMutableTreeNode whose userObject is the specified obj.

Demo Code


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

import java.util.Iterator;

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

import javax.swing.tree.TreeModel;

public class Main {
    /**//from  w  ww .  j a  v  a  2 s . c  o  m
     * Search a DefaultMutableTreeNode whose userObject is the specified obj.
     * @param obj the userObject.
     * @param tree the JTree whose TreeNodes are DefaultMutableTreeNodes.
     * @return a DefaultMuatbleTreeNode whose userObject is obj.
     */
    public static DefaultMutableTreeNode searchNode(Object obj, JTree tree) {
        TreeModel model = tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model
                .getRoot();
        if (root.getUserObject() == obj)
            return root;
        return searchNode(obj, root);
    }

    /**
     * A recursive method to search a DefaultMutableTreeNode that displays
     * an Object obj. 
     */
    public static DefaultMutableTreeNode searchNode(Object obj,
            DefaultMutableTreeNode parentNode) {
        DefaultMutableTreeNode treeNode = null;
        int size = parentNode.getChildCount();
        // A list of nodes with children
        java.util.List parentNodes = new ArrayList();
        for (int i = 0; i < size; i++) {
            treeNode = (DefaultMutableTreeNode) parentNode.getChildAt(i);
            if (treeNode.getUserObject() == obj)
                return treeNode;
            if (treeNode.getChildCount() > 0)
                parentNodes.add(treeNode);
        }
        for (Iterator it = parentNodes.iterator(); it.hasNext();) {
            treeNode = searchNode(obj, (DefaultMutableTreeNode) it.next());
            if (treeNode != null)
                return treeNode;
        }
        return null;
    }
}

Related Tutorials