tags:

views:

217

answers:

2

As the question states, I'd like to set a mouse listener to my JTree so that I can change the cursor to a HAND_CURSOR when the user places their mouse over a node.

I already have a MouseAdapter registered on my JTree to handle click events, but I can't seem to get a MouseMoved or MouseEntered/MouseExited to work with what I'm trying to do.

Any suggestions?

+2  A: 

You need to add a MouseMotionListener/Adapter:

tree.addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        int x = (int) e.getPoint().getX();
        int y = (int) e.getPoint().getY();
        TreePath path = tree.getPathForLocation(x, y);
        if (path == null) {
            tree.setCursor(Cursor.getDefaultCursor());
        } else {
            tree.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }
    }
});
netzwerg
Wow, this works great. I never thought to use a MouseMotionAdapter. Care to explain why this works and not a MouseAdapter using mouseMoved?
thedude19
netzwerg
+1  A: 

In a JTree, each of tree node is showed by a label generated by the TreeCellRenderer associated to this tree. The usually used class is DefaultTreeCellRenderer which renders this (the DefaultTreeCellRenderer). As a consequence, you can try adding this DefaultTreeCellRenderer a MouseMotionListener to toggle mouse cursor.

Notice adding MouseMotionListener to the tree will simply toggle mouse rendering when on Tree component, not when mouse is on a label.

Riduidel