我已经阅读了一堆已经问过的问题,但尚未看到一个可靠的答案。我试图在jTree上设置选择,以尝试为我的Java项目创建一种API。我可以轻松地在父节点上设置选择: myTree.setSelection(1);
关闭子节点的任何叶子都有问题。我有一个步行功能,我正在寻找一个特定的字符串。当我到达具有我正在寻找的字符串的节点时,我设法返回了一个Object []。但是我无法将其转换为Treepath以使用myTree.setSelectionPath(path)。任何人都可以帮忙吗?我很感激。
//My call
TreeModel model = jTree1.getModel();
Object getNode = myWalk(model);
jTree1.setSelectionPath((TreePath) getNode);
//this throw an error stating that Object[] can't be converted to a path.
public Object[] myWalk(TreeModel model, String s, String t){
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
DefaultMutableTreeNode child;
TreeNode[] returnPath = null;
int childrenCount = root.getChildCount();
for(int i = 0; i < childrenCount; i++){
child = (DefaultMutableTreeNode) root.getChildAt(i);
if(child.toString().equals(s)){
System.out.println(child.toString());
int secondChildCount = child.getChildCount();
DefaultMutableTreeNode secondLevelChild;
for(int y = 0; y < secondChildCount; y++){
secondLevelChild = (DefaultMutableTreeNode) child.getChildAt(y);
if(secondLevelChild.toString().equals(t)){
System.out.println(secondLevelChild.toString());
returnPath = secondLevelChild.getPath();
//returnPath = new TreePath(new Object[] {root.toString(), child.toString(), secondLevelChild.toString()});
}
}
}
}
return returnPath;
}
答案 0 :(得分:1)
所以解决方案最终很简单。我只需要创建一个新的TreePath with和Object数组(我没有这样做)。
所以它看起来像:
TreeModel model = jTree1.getModel();
Object[] getNode = Walk(model, "sports", "basketball");
TreePath tPath = new TreePath(getNode);
jTree1.setSelectionPath(tPath);