javainput

What Is The Difference Between BUTTON1_MASK and BUTTON1_DOWN_MASK?


From the java website:

BUTTON1_DOWN_MASK = The Mouse Button1 extended modifier constant.
BUTTON1_MASK = The Mouse Button1 modifier constant.

I'm not even sure what a "modifier constant" is. Let alone an extended one. I do understand however that BUTTON1_MASK is just the integer representation for when the left mouse button is clicked.


Solution

  • 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