Java Reference
In-Depth Information
Swing-Specific Event Handling
Keeping in mind that the Swing components are built on top of the AWT libraries, the Swing
component library has several improved capabilities to make event handling much easier. The
capabilities improve on several of AWT's core event-handling features, from basic action listening
to focus management.
To simplify event handling, the Swing library extends the original
ActionListener
interface
with the
Action
interface to store visual attributes with the event handler. This allows the creation
of event handlers independent of visual components. Then, when the
Action
is later associated
with a component, the component automatically gets information (such as a button label)
directly from the event handler. This includes notification of updates for the label when the
Action
is modified. The
AbstractAction
and
TextAction
classes are implementations of this
concept.
The Swing library also adds a
KeyStroke
class that allows you to more easily respond to key
events. Instead of watching all key events for a specific key, you can tell a component that when
a specific keystroke sequence is pressed, it must respond with a particular action. These
keystroke-to-action mappings are stored in a combination of
InputMap
and
ActionMap
objects.
The
InputMap
is specifically a
ComponentInputMap
when the component's window has the focus. The
Swing text components can use these more readily to store the mapping of keystrokes to actions
with the help of the
Keymap
interface. The mappings for the
TextAction
support are described
in more detail in Chapter 16, along with the remainder of the text event-handling capabilities.
The
KeyboardFocusManager
and
DefaultKeyboardFocusManager
, along with the help of the
FocusTraversalPolicy
and its implementations, manage the focus subsystem. The
InputVerifier
helps, too, for validation of user input. These are discussed in the “Swing Focus Management”
section later in this chapter.
Action Interface
The
Action
interface is an extension to the
ActionListener
interface that's very flexible for
defining shared event handlers independent of the components that act as the triggering agents.
The interface implements
ActionListener
and defines a lookup table data structure whose
keys act as bound properties. Then, when an
Action
is associated with a component, these
display properties are automatically carried over to it. The following is the interface definition:
public interface Action implements ActionListener {
// Constants
public final static String ACCELERATOR_KEY;
public final static String ACTION_COMMAND_KEY;
public final static String DEFAULT;
public final static String LONG_DESCRIPTION;
public final static String MNEMONIC_KEY;
public final static String NAME;
public final static String SHORT_DESCRIPTION;
public final static String SMALL_ICON;