Java Notes

Mouse Buttons, Modifier Keys

Mouse Buttons. Java supports up to three mouse buttons. Even if your mouse doesn't have three separate buttons, you can simulate some of the buttons by pressing modifier keys when pressing the mouse button.

The MouseEvent object that is passed to the listener contains information that allows you to ask which combinations of buttons were pressed when the event occurred. Mouse scroll controls were first supported in Java 2 SDK 1.4.

There are two ways to test the mouse buttons and modifier keys:

To Use Methods to Check Mouse Buttons

To check which mouse button is pressed, call one of the static methods in SwingUtilities. These methods return true if the corresponding button is being used. Note that more than one of them will be true if more than one button is in use at the same time.

To Use Methods to Check Modifier Keys

To check which modifier keys are pressed, use these methods in the MouseEvent class:

  boolean isAltDown()     // true if Alt key middle mouse button
  boolean isControlDown() // true if Control key is pressed
  boolean isShiftDown()   // true if Shift key is pressed
  boolean isAltGraphDown()// true if Alt Graphics key (found on some keyboards) is pressed
  boolean isMetaDown()    // true if Meta key or right mouse button

For example, inside the mouse listener we could make a test like the following to see if the right mouse button is pressed while the shift key is down. Assume that e is a MouseEvent object.

    if (SwingUtilities.isRightMouseButton(e) && e.isShiftDown())

To Use Bit Masks to Check Mouse Buttons and Modifier Keys

Use the MouseEvent getModifiers() method to get the a bitmask which tells which buttons were pressed when the event occurred. The masks for each of the mouse buttons as well as modifier keys are:
InputEvent.BUTTON1_MASKmouse button1
InputEvent.BUTTON2_MASKmouse button2
InputEvent.BUTTON3_MASKmouse button3
InputEvent.ALT_MASKalt key
InputEvent.CTRL_MASKcontrol key
InputEvent.SHIFT_MASKshift key
InputEvent.META_MASKmeta key
InputEvent.ALT_GRAPH_MASKalt-graph key

To rewrite the previous example using bit masks to test whether the right mouse button is pressed while the shift key is down, we could do the following:
    int RIGHT_SHIFT_MASK = InputEvent.BUTTON3_MASK + InputEvent.SHIFT_MASK;
    . . .
    if ((e.getModifiers() & RIGHT_SHIFT_MASK) == RIGHT_SHIFT_MASK) {