The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.tree  [15 examples] > Nodes  [6 examples]

e1028. Converting All Nodes in a JTree Component to a TreePath Array

    // If expanded, return only paths of nodes that are expanded.
    public TreePath[] getPaths(JTree tree, boolean expanded) {
        TreeNode root = (TreeNode)tree.getModel().getRoot();
    
        // Create array to hold the treepaths
        List list = new ArrayList();
    
        // Traverse tree from root adding treepaths for all nodes to list
        getPaths(tree, new TreePath(root), expanded, list);
    
        // Convert list to array
        return (TreePath[])list.toArray(new TreePath[list.size()]);
    }
    public void getPaths(JTree tree, TreePath parent, boolean expanded, List list) {
        // Return if node is not expanded
        if (expanded && !tree.isVisible(parent)) {
            return;
        }
    
        // Add node to list
        list.add(parent);
    
        // Create paths for all children
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration e=node.children(); e.hasMoreElements(); ) {
                TreeNode n = (TreeNode)e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                getPaths(tree, path, expanded, list);
            }
        }
    }

 Related Examples
e1023. Visiting All the Nodes in a JTree Component
e1024. Finding a Node in a JTree Component
e1025. Adding a Node to a JTree Component
e1026. Removing a Node to a JTree Component
e1027. Converting a Node in a JTree Component to a TreePath

See also: Events    Layout    Node Expansion    Selections   


© 2002 Addison-Wesley.