# Regarding Jtree How can I expand and collapse a complete JTree (including all subtress) programmatically?

Created May 7, 2012

**Doug Bell**

You would think this would be simple, and perhaps part of the JTree functionality, but it's not as simple as it should be. I've never required the ability to programatically collapse a tree, so thus I can only provide the solution to programatically expand a JTree. The solution below can also be used to programatically expand any node of the tree. You can limit the depth of expansion as well.

The code to programatically collapse the tree is quite similar and you should be able to work it out from the code below.

/** * Expands all nodes in a JTree. * * @param tree The JTree to expand. * @param depth The depth to which the tree should be expanded. Zero * will just expand the root node, a negative value will * fully expand the tree, and a positive value will * recursively expand the tree to that depth. */ public static void expandJTree (javax.swing.JTree tree, int depth) { javax.swing.tree.TreeModel model = tree.getModel(); expandJTreeNode(tree, model, model.getRoot(), 0, depth); } // expandJTree() /** * Expands a given node in aJTree. * * @param tree TheJTreeto expand. * @param model TheTreeModelfortree. * @param node The node withintreeto expand. * @param row The displayed row intreethat represents *node. * @param depth The depth to which the tree should be expanded. * Zero will just expandnode, a negative * value will fully expand the tree, and a positive * value will recursively expand the tree to that * depth relative tonode. */ public static int expandJTreeNode (javax.swing.JTree tree, javax.swing.tree.TreeModel model, Object node, int row, int depth) { if (node != null && !model.isLeaf(node)) { tree.expandRow(row); if (depth != 0) { for (int index = 0; row + 1 < tree.getRowCount() && index < model.getChildCount(node); index++) { row++; Object child = model.getChild(node, index); if (child == null) break; javax.swing.tree.TreePath path; while ((path = tree.getPathForRow(row)) != null && path.getLastPathComponent() != child) row++; if (path == null) break; row = expandJTreeNode(tree, model, child, row, depth - 1); } } } return row; } // expandJTreeNode()