简体   繁体   English

如何检查Swing中是否按下了哪个鼠标按钮

[英]How to check if and which mouse button is pressed in Swing

How can I check if currently any mouse button is pressed and if so, which one it is? 我如何检查当前是否按下了鼠标按钮,如果按下了,是哪一个?

The thing is that I need to use this kind of information in MouseListener.mouseEntered() . 问题是我需要在MouseListener.mouseEntered()使用这种信息。 I checked MouseEvent but I could not find the method which would help me. 我检查了MouseEvent但是找不到可以帮助我的方法。

The getButton() method seems to only return value if there has been change in buttons' state. 如果按钮状态发生变化,则getButton()方法似乎仅返回值。

Is there a way to find this out without manually keeping track of this somehow vie MouseListener.mousePressed()/mouseReleased() methods. 有没有一种方法可以找到此结果,而无需手动跟踪MouseListener.mousePressed()/mouseReleased()方法。

How can I check if currently any mouse button is pressed and if so, which one it is? 我如何检查当前是否按下了鼠标按钮,如果按下了,是哪一个?

Presumably you want to invoke specific code depending on the button pressed so you can do something like: 大概您想根据所按下的按钮来调用特定的代码,因此您可以执行以下操作:

if (SwingUtilities.isLeftMouseButton(...))
   // do something

You could start by looking at How to write a Mouse Listener and the JavaDocs for MouseEvent in particular, the getButton method. 您可以从如何编写鼠标侦听器以及如何 为MouseEvent 编写 JavaDocs (特别是getButton方法)开始。

However, there are cross platform considerations that need to taken into consideration, which are overed by SwingUtilities.isLeftMouseButton and equivalent methods... 但是,需要考虑跨平台的注意事项,而SwingUtilities.isLeftMouseButton和等效方法对此有影响。

This will solve your problem 这将解决您的问题

    long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK + AWTEvent.MOUSE_EVENT_MASK;

    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
        public void eventDispatched(AWTEvent e) {
            System.out.println(e.paramString()+"-"+e.getSource());
        }
    }, eventMask);

This is a Global Event Listeners . 这是一个全局事件监听器

Get the source and button from AWTEvent and do whatever you want to perform. AWTEvent获取源代码和按钮,然后执行您想执行的所有操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM