Java Reference
In-Depth Information
Once the
Action
has been defined, you can create the
Action
and associate it with as many
other components as you want.
Action printAction = new PrintHelloAction();
menu.add(new JMenuItem(printAction));
toolbar.add(new JButton(printAction));
After the
Action
has been associated with the various objects, if you find that you need to
modify the properties of the
Action
, you need to change the setting in only one place. Because
the properties are all bound, they propagate to any component that uses the
Action
. For instance,
disabling the
Action
(
printAction.setEnabled(false)
) will disable the
JMenuItem
and
JButton
created on the
JMenu
and
JToolBar
, respectively. In contrast, changing the name of the
Action
with
printAction.putValue(Action.NAME, "Hello, World")
changes the text label of the asso-
ciated components.
Figure 2-6 shows what the
PrintHelloAction
might look like on a
JToolBar
and a
JMenu
.
Selectable buttons are provided to enable or disable the
Action
, as well as to change its name.
Figure 2-6.
The PrintHelloAction in use
The complete source code for this example follows in Listing 2-9. Don't worry just yet
about the specifics of creating toolbars and menu bars. They'll be discussed in more detail
in Chapter 6.
Listing 2-9.
PrintHelloAction Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionTester {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Action Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Action printAction = new PrintHelloAction();
JMenuBar menuBar = new JMenuBar();