Converting All Nodes in a JTree Component to a TreePath Array

// If expanded, return only paths of nodes that are expanded. public TreePath[] getPaths(JTree tree, boolean expanded) { TreeNode root = (TreeNode)tree.getModel().getRoot(); // Create array to hold the treepaths List list = new ArrayList(); // Traverse tree from root adding treepaths for all nodes to list getPaths(tree, new TreePath(root), expanded, list); // Convert list to array return (TreePath[])list.toArray(new TreePath[list.size()]); } 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); } } }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.