简体   繁体   English

如何将鼠标监听器添加到JTree,以便在将鼠标悬停在节点上时可以更改光标(到手形光标)?

[英]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来处理点击事件,但我似乎无法使用MouseMovedMouseEntered / 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.

相关问题 将鼠标光标悬停在JTree中的节点上 - Change mouse cursor on hover over node in JTree 在将鼠标悬停在Selenium中的链接上时,是否将鼠标光标更改为手形? - Check if mouse cursor changed to a hand while hovering over a link in Selenium? 将鼠标悬停在JSplitPane分频器上时更改光标 - Change cursor when hovering over JSplitPane divider 如果鼠标悬停在jdatepicker按钮上,如何更改鼠标光标 - How to change mouse cursor if mouse is over jdatepicker button 想要在JTree列出的元素上更改鼠标移动上的光标 - want to change the cursor on mouse move on JTree listed elements 在对象上滚动时鼠标光标不会改变 - Mouse cursor won't change when rolling over objects Java / Swing:鼠标悬停在组件上方时不会发生变化 - Java/Swing: Mouse cursor doesn't change when over component 当鼠标移至2个面板的交叉区域时,更改光标 - Change the cursor when the mouse's over the intersection area of 2 panels 预熔。 将鼠标悬停在节点上时,如何更改连接边的可视化效果? - Prefuse. When hovering over a node, how can I change the connected edges' visualization? 如何查看鼠标光标是否悬停在 java graphics2D 翻译对象上 - How to see if mouse cursor is hovering over a java graphics2D translated object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM