Responding to Keyboard Input
Swing provides a flexible framework for keyboard-based control, which can be used by any component. The rest of the chapter explains this mechanism.
The InputMap Class
InputMap
maps keystrokes to logical action names. When the user types
a key combination, it’s looked up in the input map of the focused
component (and perhaps other components in the active window, as
described earlier). If a match is found, the resulting object is used
as a key in the corresponding component’s ActionMap
to look up the concrete Action
class to be invoked. The
platform-specific L&F implementations provide InputMap
s consistent with the key-binding
conventions for their platforms.
When looking for values in an InputMap
, a java.awt.KeyStroke
is always used as the
key. KeyStroke
is a simple,
immutable class that represents a particular keyboard action
(including any modifier keys). KeyStroke
s are intended to be unique (that
is, if two KeyStroke
variables
represent the same action, they should reference the same KeyStroke
instance). To ensure uniqueness,
you can’t create KeyStroke
s
directly; you must obtain them through the static getKeyStroke( )
factory methods in the
KeyStroke
class.
Although the result of looking up a KeyStroke
in an InputMap
is an arbitrary object, and any
object can be used as a key for looking up an action in an ActionMap
, in practice the values are
String
s. By convention, their
content is a descriptive name for the action to be performed (such as
copy
, ...
Get Java Swing, 2nd Edition 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.