Java Reference
In-Depth Information
specific keys to be pressed. The KeyStroke class allows you to define a single combination of
keystrokes, such as Shift-Ctrl-P or F4. You can then activate the keystroke by registering it with
a component and telling the keystroke what to do when the component recognizes it, causing
the ActionListener to be notified.
Before finding out how to create keystrokes, let's look at the different conditions that can
be activated and thus added to different input maps. Three conditions can activate a registered
keystroke, and there are four constants in JComponent to help. The fourth is for an undefined
state. The four available constants are listed in Table 2-4.
Table 2-4. Keystroke Registration Conditions
Constant
Description
WHEN_FOCUSED
Activates the keystroke when the actual component
has the input focus
WHEN_IN_FOCUSED_WINDOW
Activates the keystroke when the window that the
component is in has the input focus
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
Activates the keystroke when pressed in the component
or a container of the component
UNDEFINED_CONDITION
For when no condition is defined
Note In the special instance in which the keystrokes are supposed to be active only when the component
is in the focused window, the InputMap is actually a ComponentInputMap .
Creating a KeyStroke
The KeyStroke class is a subclass of AWTKeyStroke and has no public constructor. You create a
keystroke by using one of the following methods:
public static KeyStroke getKeyStroke(char keyChar)
public static KeyStroke getKeyStroke(String representation)
public static KeyStroke getKeyStroke(int keyCode, int modifiers)
public static KeyStroke getKeyStroke(int keyCode, int modifiers,
boolean onKeyRelease)
public static KeyStroke getKeyStrokeForEvent(KeyEvent keyEvent)
The first version in this list, public static KeyStroke getKeyStroke(char keyChar) , allows
you to create a keystroke from a char variable, such as Z .
KeyStroke space = KeyStroke.getKeyStroke('Z');
 
Search WWH ::




Custom Search