O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 InputMaps 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). KeyStrokes 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 KeyStrokes 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 Strings. By convention, their content is a descriptive name for the action to be performed (such as copy, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required