Java Reference
In-Depth Information
■
Note
I prefer to avoid using a
char
variable to create a keystroke, because you don't know whether to
specify an uppercase or lowercase letter. There is also an outdated, or deprecated, version of this method that
adds a
boolean onKeyRelease
argument. This, too, should be avoided.
The
public static KeyStroke getKeyStroke(String representation)
version is the most
interesting of the lot. It allows you to specify a keystroke as a text string, such as
"control F4"
.
The set of modifiers to the string are
shift
,
control
,
meta
,
alt
,
button1
,
button2
, and
button3
,
and multiple modifiers can be specified. The remainder of the string comes from one of the
many
VK_*
constants of the
KeyEvent
class. For example, the following defines a keystroke for
Ctrl-Alt-7:
KeyStroke controlAlt7 = KeyStroke.getKeyStroke("control alt 7");
The
public static KeyStroke getKeyStroke(int keyCode, int modifiers)
and
public
static KeyStroke getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease)
methods are the most straightforward. They allow you to directly specify the
VK_*
key constant
and the
InputEvent
masks for the modifiers (or zero for no modifiers). When not specified,
onKeyRelease
is
false
.
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true);
KeyStroke shiftF4 = KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.SHIFT_MASK);
The last version listed,
public static KeyStroke getKeyStrokeForEvent(KeyEvent keyEvent)
,
maps a specific
KeyEvent
directly to a
KeyStroke
. This is useful when you want to allow a user to
supply the keystroke to activate an event. You ask the user to press a key for the event, and then
register the
KeyEvent
so that the next time it happens, the event is activated.
KeyStroke fromKeyEvent = KeyStroke.getKeyStrokeForEvent(keyEvent);
Registering a KeyStroke
After you've created the keystroke, you need to register it with a component. When you register
a keystroke with a component, you provide an
Action
to call when pressed (or released). Regis-
tration involves providing a mapping from keystroke to
Action
. First, you get the appropriate
InputMap
for the component based on the focus activation condition (from Table 2-4) with
getInputMap(condition)
. If no condition is provided,
WHEN_FOCUSED
is assumed. You then add a
mapping from keystroke to text string in the
InputMap
:
component.getInputMap().put(keystroke, string)
If you know the action string for an existing action, you can use that; otherwise, you define
the string. You then work with the
ActionMap
to map that string to an
Action
:
component.getActionMap.put(string, action)