Java Reference
In-Depth Information
ActionListener cutListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
aTextComponent.cut();
}
};
However, there is an easier way that doesn't require you to manually create the
ActionListener implementations. This method involves finding an existing cut action by
asking the text component. If you look at the set of JTextComponent properties in Table 15-1,
you'll notice one property named actions , which is an array of Action objects. This property
contains a predefined set of Action implementations that you can directly associate as an
ActionListener with any button or menu item. Once you get the current actions for the text
component, you can go through the array until you find the appropriate one. Because actions
are named, you merely need to know the text string for the name. The DefaultEditorKit class
has about 40 keys as public constants. Here is an example of getting the cut action:
Action actions[] = textField.getActions();
Action cutAction = TextUtilities.findAction(actions, DefaultEditorKit.cutAction);
All actions in the set for a text component are a type of TextAction , which is an extension
of the AbstractAction class. The essential thing to know about a TextAction is that it acts on the
last focused text component. (The TextAction class, along with the DefaultEditorKit , will be
discussed more extensively in Chapter 16.) So, even though the preceding source fragment
acquires the cut action from a text field, the same cut action would work for another text
component on the same screen. Whichever text component had the input focus last would be
the one cut when the specific cutAction is activated.
To help you visualize this behavior, Figure 15-7 shows a screen with a JTextField at the
top, a JTextArea in the middle, and buttons on the bottom for the cut, copy, and paste opera-
tions (although these operations are more commonly available through an Edit menu). If you
run the program, you'll notice that the cut, copy, and paste actions act on the last focused text
component.
Figure 15-7. Accessing the system clipboard from a text component
The source code in Listing 15-4 is the complete example for finding an Action in the
actions property array and using cut, copy, and paste.
 
Search WWH ::




Custom Search