public static void collapseAll(final JTree tree, final int keepSelectionLevel) { final TreePath leadSelectionPath = tree.getLeadSelectionPath(); // Collapse all int row = tree.getRowCount() - 1; while (row >= 0) { tree.collapseRow(row); row--; } final DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot(); tree.expandPath(new TreePath(root)); if (leadSelectionPath != null) { final Object[] path = leadSelectionPath.getPath(); final Object[] pathToSelect = new Object [path.length > keepSelectionLevel && keepSelectionLevel >= 0 ? keepSelectionLevel : path.length]; System.arraycopy(path, 0, pathToSelect, 0, pathToSelect.length); if (pathToSelect.length == 0) return; selectPath(tree, new TreePath(pathToSelect)); } }
/** Collapse the tree so that only the root node is visible. */ public void collapseTree() { for (int i = 1; i < resultsTree.getRowCount(); ++i) { resultsTree.collapseRow(i); } }