(1)实现一个扩展于AbstractAction类的类。多个相关的动作可以使用同一个类。
(2)构造一个动作类的对象。
(3)使用动作对象创建按钮或菜单项。构造器将从动作对象中读取标签文本和图标。
(4)为了能够通过触发出发动作,必须额外的执行几步操作。首先定位顶层窗口组件,例如,包含所有其他组件的面板。
(5)然后,得到顶层组件的WHEN_ANCESTOR_OF_FOCUS_COMPONENT输入映射。为需要的击键创建一个KeyStrike对象。创建一个描述动作字符串这样的动作键对象。将(击键,动作键)对添加到输入映射中。
(6)最后,得到顶层组件的动作映射。将(动作键、动作对象)添加到映射中。
1
2
3
4
5
6
7
8
9
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
59
60
61
62
|
package JavaSwing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ActionTest { public static void main(String[] args){ EventQueue.invokeLater( new Runnable(){ public void run(){ ActionFrame frame = new ActionFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible( true ); } } ); } } class ActionFrame extends JFrame{ public ActionFrame(){ setTitle( "ActionTest" ); setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); buttonPanel = new JPanel(); Action yellowAction = new ColorAction( "Yellow" , new ImageIcon( "yellow-ball.gif" ),Color.YELLOW); Action blueAction = new ColorAction( "Blue" , new ImageIcon( "blue-ball.gif" ),Color.BLUE); Action redAction = new ColorAction( "Red" , new ImageIcon( "red-ball.gif" ),Color.RED); buttonPanel.add( new JButton(yellowAction)); buttonPanel.add( new JButton(blueAction)); buttonPanel.add( new JButton(redAction)); add(buttonPanel); InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); imap.put(KeyStroke.getKeyStroke( "Ctrl Y" ), "panel.yellow" ); imap.put(KeyStroke.getKeyStroke( "Ctrl B" ), "panel.blue" ); imap.put(KeyStroke.getKeyStroke( "Ctrl R" ), "panel.red" ); ActionMap amap = buttonPanel.getActionMap(); amap.put( "panel.yellow" , yellowAction); amap.put( "panel.blue" , blueAction); amap.put( "panel.red" , redAction); } public class ColorAction extends AbstractAction{ public ColorAction(String name,Icon icon,Color c){ putValue(Action.NAME,name); putValue(Action.SMALL_ICON,icon); putValue( "color" ,c); } public void actionPerformed(ActionEvent event){ Color c = (Color)getValue( "color" ); buttonPanel.setBackground(c); } } private JPanel buttonPanel; public static final int DEFAULT_WIDTH = 300 ; public static final int DEFAULT_HEIGHT = 200 ; } |