Traverse all expanded nodes in tree in Java
Description
The following code shows how to traverse all expanded nodes in tree.
Example
//from w w w . j a v a2 s . c o m
import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String[] argv) throws Exception {
JTree tree = new JTree();
visitAllExpandedNodes(tree);
}
public static void visitAllExpandedNodes(JTree tree) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
visitAllExpandedNodes(tree, new TreePath(root));
}
public static void visitAllExpandedNodes(JTree tree, TreePath parent) {
if (!tree.isVisible(parent)) {
return;
}
TreeNode node = (TreeNode) parent.getLastPathComponent();
System.out.println(node);
if (node.getChildCount() >= 0) {
for (Enumeration e = node.children(); e.hasMoreElements();) {
TreeNode n = (TreeNode) e.nextElement();
TreePath path = parent.pathByAddingChild(n);
visitAllExpandedNodes(tree, path);
}
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »