Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mouseDragged not returning appropriate button down

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.

like image 740
Sean_A91 Avatar asked Jul 03 '13 06:07

Sean_A91


3 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) {
    // ...
}
like image 182
Jacob Raihle Avatar answered Oct 17 '22 22:10

Jacob Raihle


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.

like image 7
user3479450 Avatar answered Oct 17 '22 23:10

user3479450


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");
    }
}
like image 2
Alex Avatar answered Oct 17 '22 23:10

Alex