Expand or Collapse all nodes in a JTree

Wednesday, 27 July 2011 14:05

Expand or collapse all nodes in a JTree

Expand or collapse all nodes in a JTree

Swing’s JTree node component can be expanded or collapsed but nothing has been provided to expand or collapse all tree nodes using a single method. The following Tree utility class provides a method to fully expand or collapse recursively walking the tree and expanding or collapsing all nodes from the bottom up.

JTree utility class to Expand or collapse all nodes in a JTree


import java.util.Enumeration;

import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 * Tree utils
 */
public class TreeUtils {

    /**
     * Expand or collapse all nodes 
     * 
     * @param tree
     * @param expand
     */
    static public void expandAll(JTree tree, boolean expand) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    expandAll(tree, new TreePath(root), expand);
    }

    /**
     * Expand all tree nodes
     * 
     * @param tree
     *         subject tree
     * @param parent
     *         parent tree path
     * @param expand
     *         expand or collapse
     */
    static private void expandAll(JTree tree, TreePath parent, boolean expand) {
    TreeNode node = (TreeNode) parent.getLastPathComponent();
    if (node.getChildCount() >= 0) {
        for (@SuppressWarnings("unchecked")
        Enumeration<TreeNode> e = node.children(); e.hasMoreElements();) {
        TreeNode treeNode = (TreeNode) e.nextElement();
        TreePath path = parent.pathByAddingChild(treeNode);
        expandAll(tree, path, expand);
        }
    }
    // Expansion or collapse must be done bottom-up
    if (expand) {
        tree.expandPath(parent);
    } else {
        tree.collapsePath(parent);
    }
    }

}

JTree related articles

Tags: tree , class , static , jtree , path , expand , collapse , @param , nodes , parent , utils , javax.swing.tree.treepath;/** , javax.swing.tree.treenode;import

Comments

0 #1 Tellmarch 2011-10-07 11:50
That code is wrong, it assumes that the Objects in the TreeModel implement TreeNode, which is not always true.

as said in http://download.oracle.com/javase/tutorial/uiswing/components/tree.html
"the TreeModel interface accepts any kind of object as a tree node. It does not require that nodes be represented by DefaultMutableT reeNode objects, or even that nodes implement the TreeNode interface."
Quote

Add comment


Security code
Refresh