[英]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?
正如問題所述,我想為我的JTree
設置鼠標監聽器,以便當用戶將鼠標放在節點上時我可以將光標更改為HAND_CURSOR
。
我已經在我的JTree上注冊了一個MouseAdapter
來處理點擊事件,但我似乎無法使用MouseMoved
或MouseEntered
/ MouseExited
來處理我正在嘗試的事情。
有什么建議么?
您需要添加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));
}
}
});
在JTree中,每個樹節點都由與此樹關聯的TreeCellRenderer
生成的標簽顯示。 通常使用的類是DefaultTreeCellRenderer
,它會渲染它( DefaultTreeCellRenderer
)。 因此,您可以嘗試添加此DefaultTreeCellRenderer
一個MouseMotionListener來切換鼠標光標。
注意,將鼠標添加到樹中只會在樹組件上切換鼠標渲染,而不是在鼠標位於標簽上時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.