[英]How to programmatically set selection on a jTree child
I've read through a bunch of questions already asked but haven't see an solid answer yet. 我已经阅读了很多已经提出的问题,但是还没有一个可靠的答案。 I'm trying to set the selection on a jTree in an attempt to create a sort of API for my Java project.
我试图在jTree上设置选择,以尝试为我的Java项目创建一种API。 I can set selection on a parent node easily with say: myTree.setSelection(1);
我可以使用以下命令轻松地在父节点上设置选择:myTree.setSelection(1);
Having trouble with any leafs off child nodes. 遇到任何麻烦都会使子节点掉下来。 I've have a walk function and I'm looking for a specific string in it.
我有一个walk函数,正在其中寻找一个特定的字符串。 I've managed to return a Object[] when I reach the node with the string I'm looking for.
当我到达要查找的字符串的节点时,我设法返回了一个Object []。 But I can't convert it to a Treepath to use myTree.setSelectionPath(path).
但是我无法将其转换为使用myTree.setSelectionPath(path)的Treepath。 Can anyone help out with this?
有人可以帮忙吗? I appreciate it.
我很感激。
//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;
}
So the solution ended up being simple. 因此,解决方案最终变得很简单。 I just need to create a new TreePath with and Object array (which I wasn't doing).
我只需要使用Object数组创建一个新的TreePath(我没有做)。
So it would look like: 因此,它看起来像:
TreeModel model = jTree1.getModel();
Object[] getNode = Walk(model, "sports", "basketball");
TreePath tPath = new TreePath(getNode);
jTree1.setSelectionPath(tPath);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.