Java examples for Swing:JTree
Converting All Nodes in a JTree Component to a TreePath Array
import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.swing.JTree; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; public class Main { 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()]); }/*from w w w .j a va2 s.c o m*/ 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); } } } }