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
  • 200,320
  • 28
  • 229
  • 974
newSpringer
  • 1,008
  • 9
  • 28
  • 43

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,198
  • 5
  • 50
  • 77
  • 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

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 .

0

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
  • 728
  • 6
  • 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