01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
package horstmann.ch10_command;
import java.awt.BorderLayout;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
/**
This program demonstrates action objects. Two actions
insert greetings into a text area. Each action can be
triggered by a menu item or toolbar button. When an
action is carried out, the opposite action becomes enabled.
*/
public class CommandTester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JMenuBar bar = new JMenuBar();
frame.setJMenuBar(bar);
JMenu menu = new JMenu("Say");
bar.add(menu);
JToolBar toolBar = new JToolBar();
frame.add(toolBar, BorderLayout.NORTH);
JTextArea textArea = new JTextArea(10, 40);
frame.add(textArea, BorderLayout.CENTER);
GreetingAction helloAction = new GreetingAction(
"Hello, World", textArea);
helloAction.putValue(Action.NAME, "Hello");
helloAction.putValue(Action.SMALL_ICON,
new ImageIcon("hello.png"));
GreetingAction goodbyeAction = new GreetingAction(
"Goodbye, World", textArea);
goodbyeAction.putValue(Action.NAME, "Goodbye");
goodbyeAction.putValue(Action.SMALL_ICON,
new ImageIcon("goodbye.png"));
helloAction.setOpposite(goodbyeAction);
goodbyeAction.setOpposite(helloAction);
goodbyeAction.setEnabled(false);
menu.add(helloAction);
menu.add(goodbyeAction);
toolBar.add(helloAction);
toolBar.add(goodbyeAction);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
|