javaswingmousemouse-listeners

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.


Solution

  • 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