Java Reference
In-Depth Information
For every text component, you need a way to associate keystrokes with specific actions.
This is done via the
Keymap
interface, which maps a
KeyStroke
to a
TextAction
, so that separate
KeyListener
objects don't need to be associated with the text component for each keystroke in
order to listen for it. Key maps can be shared across multiple components and/or customized
for a particular look and feel. The
JTextComponent
also has
getKeymap()
and
setKeymap()
methods
that allow you to read or customize the key map.
Note
Although the Swing text components use
TextAction
,
KeyStroke
, and
Keymap
, they still support
the ability to attach a
KeyListener
. Using a
KeyListener
, however, usually isn't appropriate, especially
when you want to restrict input to match certain criteria. The better approach for restricting input is to come
up with a custom
DocumentFilter
, as demonstrated in Chapter 15, or use an
InputVerifier
. In addition,
the actual
Keymap
implementation is just a wrapper to the
InputMap
/
ActionMap
combination used for
keyboard-action mapping in the nontextual Swing components.
■
The text components come with many predefined
TextAction
implementations. Through
a default key map, the text components know about these predefined actions, so they know
how to insert and remove content, as well as how to track the positions of both the cursor and
caret. If the text component supports stylized content, as
JTextPane
does, there are additional
default actions to support this content. All these implementations derive from the JFC/Swing
technology editor kits. As discussed in the “The Editor Kits” section later in this chapter, an
editor kit provides a logical grouping of the various ways to edit a specific type of text component.
Listing Actions
To find out which actions a
JTextComponent
supports, you merely ask by using the
public
Action[ ] getActions()
method. This will return an array of
Action
objects, usually of type
TextAction
, that can be used like any other
Action
, such as for creating buttons on a
JToolBar
.
Figure 16-1 shows a program that will list the actions for the different predefined components.
Pick a component from the
JRadioButton
group, and its list of text actions will be displayed in
the text area. For each action, the program shows the action name and class name.
Figure 16-1.
TextAction list demonstration