public static void ensureSelection(JTree tree) { final TreePath[] paths = tree.getSelectionPaths(); if (paths != null) { for (TreePath each : paths) { if (tree.getRowForPath(each) >= 0 && tree.isVisible(each)) { return; } } } for (int eachRow = 0; eachRow < tree.getRowCount(); eachRow++) { TreePath eachPath = tree.getPathForRow(eachRow); if (eachPath != null && tree.isVisible(eachPath)) { tree.setSelectionPath(eachPath); break; } } }
public void getPaths(JTree tree, TreePath parent, boolean expanded, List list) { // Return if node is not expanded if (expanded && !tree.isVisible(parent)) { return; } // Add node to list list.add(parent); // Create paths for all children TreeNode node = (TreeNode) parent.getLastPathComponent(); if (node.getChildCount() >= 0) { for (Enumeration e = node.children(); e.hasMoreElements(); ) { TreeNode n = (TreeNode) e.nextElement(); TreePath path = parent.pathByAddingChild(n); getPaths(tree, path, expanded, list); } } }