Double-click a JTree node and get its name

Adrian Stamin picture Adrian Stamin · Oct 11, 2012 · Viewed 18.5k times · Source

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.

Answer

MadProgrammer picture MadProgrammer · Oct 11, 2012

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.