JTree:如何获取所选节点的路径

时间:2012-07-16 17:47:23

标签: java swing jtree

有没有办法在JTree中获取所选节点的选定路径,例如使用

之类的东西
String pathForNode = JTree.getLastSelectedPathComponent().getPath().toString();

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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中,过去直截了当地为我提供了直观的方法。

答案 2 :(得分: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;
        }
    }