简体   繁体   中英

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.

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");
    }
}

This could be possibly a problem of your java sandbox.

The following code works well all the time (almost, as you can see).

@Override
public void mouseDragged(MouseEvent e) {
    e.getButton();
}

Please try your code on a different machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM