Java tutorial
//package com.java2s; import javax.swing.*; import javax.swing.tree.*; public class Main { /** * Expand (or collapse) the children nodes of specified node of a JTree for a certain depth. * @param tree Tree of which we want to expand the nodes. * @param parent Parent node. * @param expand <code>true</code> to expand the nodes. <code>false</code> to collapse the nodes. * @param depth Depth of children to expand or collapse. */ public static void expandNodes(JTree tree, TreePath parent, boolean expand, int depth) { if (parent == null || depth == 0) return; Object node = parent.getLastPathComponent(); if (node != null) { for (int i = 0; i < tree.getModel().getChildCount(node); i++) { Object child = tree.getModel().getChild(node, i); TreePath path = parent.pathByAddingChild(child); expandNodes(tree, path, expand, depth - 1); } } if (expand) tree.expandPath(parent); else tree.collapsePath(parent); } }