5

Is there a way to get the selected path of a selected node in a JTree like using something like

String pathForNode = JTree.getLastSelectedPathComponent().getPath().toString();
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
newSpringer
  • 1,018
  • 10
  • 28
  • 44

3 Answers3

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

Edit:

Try

  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

Sully
  • 14,672
  • 5
  • 54
  • 79
  • this only seems to work for the very first click on the JTree i do, this does not work for the rest of the clicks... would you know why? – newSpringer Jul 16 '12 at 18:16
  • This will work once if you re-initialized the tree. Feel free to post your code. – Sully Jul 16 '12 at 19:11
1

I used this:

    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;
        }
    }
karrtojal
  • 796
  • 7
  • 16
  • Thank you for this. This is why I really hate JTree. The methods `getPath()` and `getPath().toString()` should do this... – Adam Hughes Dec 22 '15 at 21:30
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

In C# .net it used to be straightforward to get the path and bit intuitive for me .