2017-07-18 67 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); 
相關問題