Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTree: How to get the path of a selected node

Tags:

java

swing

jtree

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();
like image 836
newSpringer Avatar asked Oct 23 '22 16:10

newSpringer


2 Answers

 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

like image 76
Sully Avatar answered Nov 08 '22 07:11

Sully


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;
        }
    }
like image 44
karrtojal Avatar answered Nov 08 '22 06:11

karrtojal