2017-07-18 90 views
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; 
    } 
+1

有一个setSelectionPath这需要将TreePath。由于您先扫描树深度,您可以简单地重新构建TreePath。 – 2017-07-19 02:06:58

回答

0

因此,解决方案最终变得简单。我只需要创建一个新的TreePath和Object数组(我没有这样做)。

因此,它看起来像:

TreeModel model = jTree1.getModel(); 
Object[] getNode = Walk(model, "sports", "basketball"); 
TreePath tPath = new TreePath(getNode); 
jTree1.setSelectionPath(tPath); 
相关问题