How can I know the button that was pressed from within a mouseDragged
event?
I'm having an issue in mouseDragged()
because the received MouseEvent
returns 0 for getButton()
. I have no problem with the mouse location, or even detecting mouse clicks. The mouseClicked()
event returns the appropriate button for getButton()
.
Any suggestions on how I can do this? I assume I could do a work-around using mouseClicked
, or mousePressed
, but I would prefer to keep this all within mouseDragged
.
Thanks for your time and answers.
As pointed out in comments and other answers, SwingUtilities provides three methods for cases like this, which should work for all MouseEvents:
SwingUtilities.isLeftMouseButton(aMouseEvent);
SwingUtilities.isRightMouseButton(aMouseEvent);
SwingUtilities.isMiddleMouseButton(aMouseEvent);
As for what the problem with your approach is, the javadoc of getButton()
says:
Returns which, if any, of the mouse buttons has changed state.
Since the state of the button doesn't change while it is being held down, getButton()
will usually return NO_BUTTON
in mouseDragged
. To check the state of buttons and modifiers like Ctrl, Alt, etc. in mouseDragged
, you can use getModifiersEx()
. As an example, the below code checks that BUTTON1
is down but BUTTON2
is not:
int b1 = MouseEvent.BUTTON1_DOWN_MASK;
int b2 = MouseEvent.BUTTON2_DOWN_MASK;
if ((e.getModifiersEx() & (b1 | b2)) == b1) {
// ...
}
Jacob's right that getButton()
doesn't get you the button by design. However, I found a cleaner solution than bit operations on getModifiersEx()
, that you can also use within mouseDragged
:
if (SwingUtilities.isLeftMouseButton(theMouseEvent)) {
//do something
}
Similar methods exist for the middle button and the right button.
int currentMouseButton = -1;
@Override
public void mousePressed(MouseEvent e) {
currentMouseButton = e.getButton();
}
@Override
public void mouseReleased(MouseEvent e) {
currentMouseButton = -1;
}
@Override
public void mouseDragged(MouseEvent e) {
if (currentMouseButton == 3) {
System.out.println("right button");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With