What Is The Difference Between BUTTON1_MASK and BU

2020-07-08 07:25发布

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.

标签: java input
2条回答
Bombasti
2楼-- · 2020-07-08 08:02

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.

查看更多
贪生不怕死
3楼-- · 2020-07-08 08:24

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

查看更多
登录 后发表回答