2012-07-16 54 views
2

的路徑有沒有辦法得到一個選擇的節點的選擇路徑在JTree喜歡使用類似JTree的:如何獲得一個選擇的節點

String pathForNode = JTree.getLastSelectedPathComponent().getPath().toString(); 
+0

另請參閱[Q&A](http://stackoverflow.com/q/8210630/230513)。 – trashgod 2012-07-17 00:09:00

回答

0

我用這個:

jTreeVarSelectedPath = ""; 
    Object[] paths = jTreeDirectorios.getSelectionPath().getPath(); 
    for (int i=0; i<paths.length; i++) { 
     jTreeVarSelectedPath += paths[i]; 
     if (i+1 <paths.length) { 
      jTreeVarSelectedPath += File.separator; 
     } 
    } 
+0

謝謝你。這就是爲什麼我真的很討厭JTree。方法'getPath()'和'getPath()。toString()'應該這樣做... – 2015-12-22 21:30:30

2
tree.addTreeSelectionListener(new TreeSelectionListener() { 
    public void valueChanged(TreeSelectionEvent e) { 
     TreePath tp = e.getNewLeadSelectionPath(); 
     if (tp != null) { 
      pathForNode = tp.getLastPathComponent(); 
     } 
    } 
}); 

http://www.coderanch.com/t/453540/GUI/java/Getting-path-file-selected-JTree

編輯:

嘗試

tree.addMouseListener(new MouseAdapter() { 
     public void mouseClicked(MouseEvent me) { 
     doMouseClicked(me); 
     } 
    }); 
    } 

    void doMouseClicked(MouseEvent me) { 
    TreePath tp = tree.getPathForLocation(me.getX(), me.getY()); 
    if (tp != null) { 
     System.out.println(tp.toString()); 
    } 
    } 

JTree path

+0

這似乎只適用於第一次點擊我的JTree,這不適用於其他點擊......你知道爲什麼嗎? – newSpringer 2012-07-16 18:16:49

+0

如果您重新初始化樹,這將會工作一次。隨意發佈您的代碼。 – 2012-07-16 19:11:42

1

See the output here

 tree.addTreeSelectionListener(new TreeSelectionListener() { 
     public void valueChanged(TreeSelectionEvent e) { 
      TreePath treepath = e.getPath(); 
      System.out.println("Java: " + treepath.getLastPathComponent()); 
      Object elements[] = treepath.getPath(); 
       for (int i = 0, n = elements.length; i < n; i++) { 
        System.out.print("->" + elements[i]); 

     // JOptionPane.showMessageDialog(null,"->"+elements[i]); 
     //lblNewLabel.setText(">"+ elements[i]); 



      value+=elements[i]+"\\"; 


     } 



     //String x=String.valueOf(value);    
     //lblNewLabel.setText(String.valueOf(value)); 

     JOptionPane.showMessageDialog(null, value); 


     //System.out.println(value); 
     } 
    }); 

    static String value=""; //add this just before the void main function 

在C#.NET它使用的是直接的獲取路徑和比特直觀的我。