How do I double-click a JTree node and get its name?
If I call evt.getSource()
it seems that the object returned is a JTree. I can't cast it to a DefaultMutableTreeNode.
From the Java Docs
If you are interested in detecting either double-click events or when a user clicks on a node, regardless of whether or not it was selected, we recommend you do the following:
final JTree tree = ...;
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
mySingleClick(selRow, selPath);
}
else if(e.getClickCount() == 2) {
myDoubleClick(selRow, selPath);
}
}
}
};
tree.addMouseListener(ml);
To get the nodes from the TreePath
you can walk the path or simply, in your case, use TreePath#getLastPathComponent
.
This returns an Object
, so you will need to cast back to the required node type yourself.