[英]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. 正如问题所述,我想为我的JTree
设置鼠标监听器,以便当用户将鼠标放在节点上时我可以将光标更改为HAND_CURSOR
。
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. 我已经在我的JTree上注册了一个MouseAdapter
来处理点击事件,但我似乎无法使用MouseMoved
或MouseEntered
/ MouseExited
来处理我正在尝试的事情。
Any suggestions? 有什么建议么?
You need to add a MouseMotionListener/Adapter
: 您需要添加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. 在JTree中,每个树节点都由与此树关联的TreeCellRenderer
生成的标签显示。 The usually used class is DefaultTreeCellRenderer
which renders this (the DefaultTreeCellRenderer
). 通常使用的类是DefaultTreeCellRenderer
,它会渲染它( DefaultTreeCellRenderer
)。 As a consequence, you can try adding this DefaultTreeCellRenderer
a MouseMotionListener to toggle mouse cursor. 因此,您可以尝试添加此DefaultTreeCellRenderer
一个MouseMotionListener来切换鼠标光标。
Notice adding MouseMotionListener to the tree will simply toggle mouse rendering when on Tree component, not when mouse is on a label. 注意,将鼠标添加到树中只会在树组件上切换鼠标渲染,而不是在鼠标位于标签上时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.