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.
InputEvent
class to look at the MouseEvent modifier bits.
This is a very fast way to check, especially for complex
combinations of modifiers and buttons, but you need to understand
the bit operators (| & ^ ~ >> >>> <<
).
boolean SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
boolean SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
boolean SwingUtilities.isRightMouseButton(MouseEvent anEvent)
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()) ...
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:
Mask | Meaning |
InputEvent.BUTTON1_MASK | mouse button1 |
InputEvent.BUTTON2_MASK | mouse button2 |
InputEvent.BUTTON3_MASK | mouse button3 |
InputEvent.ALT_MASK | alt key |
InputEvent.CTRL_MASK | control key |
InputEvent.SHIFT_MASK | shift key |
InputEvent.META_MASK | meta key |
InputEvent.ALT_GRAPH_MASK | alt-graph key |
int RIGHT_SHIFT_MASK = InputEvent.BUTTON3_MASK + InputEvent.SHIFT_MASK; . . . if ((e.getModifiers() & RIGHT_SHIFT_MASK) == RIGHT_SHIFT_MASK) { ...