Responding to Shift-Click Events
Sometimes you must respond to mouse events that occur in combination with keystrokes. For example, some interfaces select text when the user holds the Shift key while dragging the mouse. For these times, there must be a mechanism that enables you to determine if a key is being pressed simultaneously with a mouse button.
How do I do that?
For this purpose MouseEvent
contains a field known
as stateMask
. This field is populated only when
the user is holding down one of the keyboard keys at the same time
the mouse is being clicked. If you want to code some action that
occurs only when the user is holding the Shift key while clicking a
mouse button:
s.addMouseListener(new MouseAdapter( ) { public void mouseDown(MouseEvent e) { if(e.stateMask==SWT.SHIFT) { Label l = new Label(s, SWT.FLAT); l.setText("Mouse Button Down at:" + e.x + " " + e.y); l.setBounds(e.x,e.y, 150,15); } } public void mouseUp(MouseEvent e) { Label l = new Label(s, SWT.FLAT); l.setText("Mouse Button up at:" + e.x + " " + e.y); l.setBounds(e.x,e.y, 150,15); } });
This code results in the Label
being created in
the mouseDown( )
method only if the user is also
holding down the Shift key. The mouseUp( )
method
creates the Label
even if the Shift key is not
pressed.
Get SWT: A Developer's Notebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.