JTree: How to get the path of a selected node

newSpringer picture newSpringer · Jul 16, 2012 · Viewed 14.3k times · Source

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();

Answer

Hitham S. AlQadheeb picture Hitham S. AlQadheeb · Jul 16, 2012
 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