How to get selected node from JTree after selecting it? [duplicate]
Asked Answered
S

1

5

Possible Duplicate:
JTree: how to get the text of selected item?

1In C# there's TreeView_afterSelect event, and i ask if in java is something like that ? I used : hierarchyPropertyChange but it runs two times...

Schistosome answered 17/1, 2013 at 19:34 Comment(1)
It seems this has already been asked and answered here, even nice code example included.Verlaverlee
M
9

You can use a TreeSelectionListener:

tree.addTreeSelectionListener(new TreeSelectionListener() {

@Override
public void valueChanged(TreeSelectionEvent e) {
   DefaultMutableTreeNode selectedNode = 
       (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); 
   ...          
  }
});
Matz answered 17/1, 2013 at 19:39 Comment(2)
If this is the first click in the tree, the tree will return a NullPointer. So this does not work for the first click in a tree.Unprintable
@Unprintable Are you sure? It works for me on the first click. docs.oracle.com/javase/8/docs/api/javax/swing/… says Returns the last path component of the selected path. It does not say "get the path that was selected previously."Rocketeer

© 2022 - 2024 — McMap. All rights reserved.