1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| package plotter.view.component.tree;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class TestLoadTree extends javax.swing.JFrame {
private JTree tree;
public TreePath getPath(TreeNode node) {
List<TreeNode> list = new ArrayList<TreeNode>();
while (node != null) {
list.add(node);
node = node.getParent();
}
Collections.reverse(list);
return new TreePath(list.toArray());
}
public TreePath findByName(JTree tree, String[] names) {
TreeNode root = (TreeNode)tree.getModel().getRoot();
return find(tree, new TreePath(root), names, 0, true);
}
private TreePath find(JTree tree, TreePath parent, Object[] nodes, int depth, boolean byName) {
TreeNode node = (TreeNode)parent.getLastPathComponent();
Object o = node;
// If by name, convert node to a string
if (byName) {
o = o.toString();
}
// If equal, go down the branch
if (o.equals(nodes[depth])) {
// If at end, return match
if (depth == nodes.length-1) {
return parent;
}
// Traverse children
if (node.getChildCount() >= 0) {
for (Enumeration<TreeNode> e=node.children(); e.hasMoreElements(); ) {
TreeNode n = e.nextElement();
TreePath path = parent.pathByAddingChild(n);
TreePath result = find(tree, path, nodes, depth+1, byName);
// Found a match
if (result != null) {
return result;
}
}
}
}
// No match at this branch
return null;
}
public TestLoadTree() {
super("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tree = new JTree();
getContentPane().setLayout(new BorderLayout());
getContentPane().add(tree, BorderLayout.CENTER);
setSize(500,400);
TreePath path3 = findByName(tree,new String[]{"JTree", "food", "bananas"});
tree.getSelectionModel().setSelectionPath(path3);
tree.setExpandsSelectedPaths(true);
tree.scrollPathToVisible(path3);
tree.expandPath(path3);
if(tree.isPathSelected(path3)) {
System.out.println(tree.getSelectionPath());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
TestLoadTree test = new TestLoadTree();
test.setVisible(true);
}
});
}
} |
Partager