thedude19
thedude19

Reputation: 2673

How to add a mouse listener to a JTree so that I can change the cursor (to a hand cursor) when hovering over a node?

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?

Upvotes: 2

Views: 5392

Answers (2)

Riduidel
Riduidel

Reputation: 22292

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.

Upvotes: 1

Rahel Lüthy
Rahel Lüthy

Reputation: 7007

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));
        }
    }
});

Upvotes: 7

Related Questions