import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.text.Position;
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();
TreePath path = findByName(tree, new String[] { "JTree", "A", "a" });
}
public static TreePath findByName(JTree tree, String[] names) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
return find(tree, new TreePath(root), names, 0);
}
private static TreePath find(JTree tree, TreePath parent, Object[] nodes, int depth) {
TreeNode node = (TreeNode) parent.getLastPathComponent();
Object o = node;
if (o.equals(nodes[depth])) {
if (depth == nodes.length - 1) {
return parent;
}
if (node.getChildCount() >= 0) {
for (Enumeration e = node.children(); e.hasMoreElements();) {
TreeNode n = (TreeNode) e.nextElement();
TreePath path = parent.pathByAddingChild(n);
TreePath result = find(tree, path, nodes, depth + 1);
if (result != null) {
return result;
}
}
}
}
return null;
}
}
|