public static List<TreePath> collectExpandedPaths(final JTree tree, TreePath path) { final ArrayList<TreePath> result = new ArrayList<TreePath>(); if (!tree.isExpanded(path)) return result; final Object lastPathComponent = path.getLastPathComponent(); final TreeModel model = tree.getModel(); if (model.isLeaf(lastPathComponent)) { result.add(path); } else { boolean pathWasAdded = false; for (int i = model.getChildCount(lastPathComponent) - 1; i >= 0; i--) { final TreePath childPath = path.pathByAddingChild(model.getChild(lastPathComponent, i)); if (model.isLeaf(lastPathComponent)) { if (!pathWasAdded) { result.add(path); pathWasAdded = true; } } else if (tree.isExpanded(childPath)) { result.addAll(collectExpandedPaths(tree, childPath)); } else { if (!pathWasAdded) { result.add(path); pathWasAdded = true; } } } } return result; }
private static boolean collectExpandedPathsImpl( final JTree tree, final Collection<TreePath> paths, final TreePath path) { final TreeModel model = tree.getModel(); final Object lastPathComponent = path.getLastPathComponent(); if (model.isLeaf(lastPathComponent)) { return false; } boolean hasExpandedChildren = false; for (int i = model.getChildCount(lastPathComponent) - 1; i >= 0; i--) { hasExpandedChildren |= collectExpandedPathsImpl( tree, paths, path.pathByAddingChild(model.getChild(lastPathComponent, i))); } if (!hasExpandedChildren) { paths.add(path); return true; } else { return false; } }
@Nullable public static Range<Integer> getExpandControlRange(final JTree aTree, final TreePath path) { TreeModel treeModel = aTree.getModel(); final BasicTreeUI basicTreeUI = (BasicTreeUI) aTree.getUI(); Icon expandedIcon = basicTreeUI.getExpandedIcon(); Range<Integer> box = null; if (path != null && !treeModel.isLeaf(path.getLastPathComponent())) { int boxWidth; Insets i = aTree.getInsets(); if (expandedIcon != null) { boxWidth = expandedIcon.getIconWidth(); } else { boxWidth = 8; } int boxLeftX = i != null ? i.left : 0; boolean leftToRight = aTree.getComponentOrientation().isLeftToRight(); int depthOffset = getDepthOffset(aTree); int totalChildIndent = basicTreeUI.getLeftChildIndent() + basicTreeUI.getRightChildIndent(); if (leftToRight) { boxLeftX += ((path.getPathCount() + depthOffset - 2) * totalChildIndent + basicTreeUI.getLeftChildIndent()) - boxWidth / 2; } int boxRightX = boxLeftX + boxWidth; box = new Range<Integer>(boxLeftX, boxRightX); } return box; }