What Is The Difference Between BUTTON1_MASK and BUTTON1_DOWN_MASK?

BUTTON1_MASK is the mask indicating an event came from button 1. BUTTON1_DOWN_MASK is conceptually similar, but is the extended version of that constant.

There are two methods that return such sets of constants: InputEvent#getModifiers() and InputEvent#getModifiersEx(), and they will return modifier constants, or extended modifier constants, respectively.

From the docs (bold is mine):

The button mask returned by InputEvent.getModifiers() reflects only the button that changed state, not the current state of all buttons ... To get the state of all buttons and modifier keys, use InputEvent.getModifiersEx().

and also (bold is mine):

Extended modifiers represent the state of all modal keys, such as ALT, CTRL, META, and the mouse buttons just after the event occurred

For example, if the user presses button 1 followed by button 2, and then releases them in the same order, the following sequence of events is generated:

MOUSE_PRESSED:  BUTTON1_DOWN_MASK
MOUSE_PRESSED:  BUTTON1_DOWN_MASK | BUTTON2_DOWN_MASK
MOUSE_RELEASED: BUTTON2_DOWN_MASK
MOUSE_CLICKED:  BUTTON2_DOWN_MASK
MOUSE_RELEASED:
MOUSE_CLICKED:

If all you want is to detect a button 1 (normally, left) click, then either of these should work:

if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) {
    System.out.println("BUTTON1_MASK");
}

if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
    System.out.println("BUTTON1_DOWN_MASK");
}

Also, you can check out this open source version of InputEvent, which has some more useful comments, and shows what's happening inside


As the docs state, BUTTON1_MASK and BUTTON1_DOWN_MASK are modifier constants, i.e. they are use in conjunction with MouseEvent#getModifiers. They are not extended but rather used as a mask values, for example

@Override
public void mousePressed(MouseEvent me) {
 if ((me.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
      System.out.println("Left button pressed.");
    }
}

BUTTON1_DOWN_MASK is used to detect the state of the mouse button whereas the BUTTON1_MASK simply helps to determine which button is pressed.

Tags:

Java

Input