Java Reference
In-Depth Information
Using Actions
So far, you've seen that there are many predefined TextAction implementations available
for the various text components, but you haven't used any of them. By making a few minor
changes to Listing 16-1, you can enhance the program in order to activate it. The modified
program is shown in Listing 16-2. With this version, when one of the radio buttons is selected,
that type of text component will be displayed where the text list of Action objects appears in
Figure 16-1. In addition, the different Action objects are added to a new JMenuBar placed at the
top of the display window.
Note In the program shown in Listing 16-2, after all the menu buttons are activated, you're stuck with
a text label that might not be exactly what you want. However, you can easily change this with the public
void setText(String label) method of JMenuItem . If you do this, remember that you need to know
what's in the menu item to change the label to something meaningful.
Listing 16-2. Enabling Text Component Actions
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class ActionsMenuBar {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
final JFrame frame = new JFrame("TextAction Usage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane scrollPane = new JScrollPane();
frame.add(scrollPane, BorderLayout.CENTER);
final JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
ActionListener actionListener = new ActionListener() {
JTextComponent component;
public void actionPerformed(ActionEvent actionEvent) {
// Determine which component selected
String command = actionEvent.getActionCommand();
if (command.equals("JTextField")) {
component = new JTextField();
 
Search WWH ::




Custom Search