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?

java, jtree, mouse

Solution

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

Problem

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?

Original source