Java tutorial
//package com.java2s; import javax.swing.JTree; import javax.swing.tree.TreePath; public class Main { /** * Saves the current expansion state of a JTree and returns it in an Enumeration for storing purposes. Example: A * JTree that has all its branches collapsed will return a TreeExpansionState of ",0". * * @param tree * Save the current expansion state of this tree * @return The current expansion state of the given tree as Enumeration<TreePath> */ public static String getTreeExpansionState(JTree tree, int row) { TreePath rowPath = tree.getPathForRow(row); StringBuilder sb = new StringBuilder(); int rowCount = tree.getRowCount(); for (int i = row; i < rowCount; i++) { TreePath path = tree.getPathForRow(i); if (i == row || isDescendant(path, rowPath)) { if (tree.isExpanded(path)) sb.append("," + String.valueOf(i - row)); } else { break; } } return sb.toString(); } /** * @return true, if path1 is a descendant of path2. Else, returns false. */ public static boolean isDescendant(TreePath path1, TreePath path2) { int count1 = path1.getPathCount(); int count2 = path2.getPathCount(); if (count1 <= count2) return false; while (count1 != count2) { path1 = path1.getParentPath(); count1--; } return path1.equals(path2); } }