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?
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));
}
}
});
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.
精彩评论