Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double-click a JTree node and get its name

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.

like image 549
Adrian Stamin Avatar asked Oct 11 '12 20:10

Adrian Stamin


1 Answers

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.

like image 128
MadProgrammer Avatar answered Sep 25 '22 23:09

MadProgrammer