问题
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