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

守給你的承諾、 提交于 2021-02-17 05:47:46

问题


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(). I checked MouseEvent but I could not find the method which would help me.

The getButton() method seems to only return value if there has been change in buttons' state.

Is there a way to find this out without manually keeping track of this somehow vie MouseListener.mousePressed()/mouseReleased() methods.


回答1:


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



回答2:


You could start by looking at How to write a Mouse Listener and the JavaDocs for MouseEvent in particular, the getButton method.

However, there are cross platform considerations that need to taken into consideration, which are overed by SwingUtilities.isLeftMouseButton and equivalent methods...




回答3:


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.



来源:https://stackoverflow.com/questions/22697846/how-to-check-if-and-which-mouse-button-is-pressed-in-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!