0
我已阅读了一堆已经问过的问题,但尚未看到一个确切的答案。我试图在jTree上设置选择,试图为我的Java项目创建一种API。我可以轻松地在父节点上设置选择,例如: myTree.setSelection(1);如何以编程方式在jTree子上设置选择
无法关闭子节点上的任何叶子。我有一个散步功能,我正在寻找一个特定的字符串。当我用正在查找的字符串到达节点时,我设法返回一个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;
}
有一个setSelectionPath这需要将TreePath。由于您先扫描树深度,您可以简单地重新构建TreePath。 – 2017-07-19 02:06:58