javaswingawtmouse-listeners

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.


Solution

  • 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) {
        // ...
    }