如果您能够找到叶子的新路径,则可以创建一个TreePath。
我举了一个例子,在 JTree 中选择一个具有一级节点的叶子:
public JTree fileTree;
public void setJTreePath(String leafName, String nodeName) {
TreeNode root = (TreeNode) fileTree.getModel().getRoot();
TreePath path = new TreePath(root);
int rootChildCount = root.getChildCount();
mainLoop:
for (int i = 0; i < rootChildCount; i++) {
TreeNode child = root.getChildAt(i);
if (child.toString().equals(nodeName)) {
path = path.pathByAddingChild(child);
int ChildCount = child.getChildCount();
for (int j = 0; j < ChildCount; j++) {
TreeNode child2 = child.getChildAt(j);
if (child2.toString().equals(leafName)) {
path = path.pathByAddingChild(child2);
fileTree.setSelectionPath(path);
//I've used a SwingUtilities here, maybe it's not mandatory
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
fileTree.scrollPathToVisible(fileTree.getSelectionPath());
}
});
break mainLoop;
}
}
}
}
}