简体   繁体   中英

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() . 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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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