grep All User Objects from JTree - Java Swing

Java examples for Swing:JTree

Description

grep All User Objects from JTree

Demo Code


//package com.java2s;

import java.util.HashSet;

import java.util.Set;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class Main {
    public static Set<Object> grepAllUserObjects(JTree tree) {
        Set<Object> rtn = new HashSet<Object>();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree
                .getModel().getRoot();//from ww  w.ja v a 2s .  co m
        grepAllUserObjects(root, rtn);
        return rtn;
    }

    private static <T> void grepAllUserObjects(
            DefaultMutableTreeNode treeNode, Set<Object> set) {
        Object obj = treeNode.getUserObject();
        if (obj != null)
            set.add(obj);
        if (treeNode.getChildCount() == 0)
            return;
        for (int i = 0; i < treeNode.getChildCount(); i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeNode
                    .getChildAt(i);
            grepAllUserObjects(child, set);
        }
    }
}

Related Tutorials