The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.tree  [15 examples] > Node Expansion  [2 examples]

e1029. Expanding or Collapsing All Nodes in a JTree Component

    // If expand is true, expands all nodes in the tree.
    // Otherwise, collapses all nodes in the tree.
    public void expandAll(JTree tree, boolean expand) {
        TreeNode root = (TreeNode)tree.getModel().getRoot();
    
        // Traverse tree from root
        expandAll(tree, new TreePath(root), expand);
    }
    private void expandAll(JTree tree, TreePath parent, boolean expand) {
        // Traverse 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);
                expandAll(tree, path, expand);
            }
        }
    
        // Expansion or collapse must be done bottom-up
        if (expand) {
            tree.expandPath(parent);
        } else {
            tree.collapsePath(parent);
        }
    }

 Related Examples
e1030. Preventing the Expansion or Collapse of a Node in a JTree Component

See also: Events    Layout    Nodes    Selections   


© 2002 Addison-Wesley.