import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ActionTest
{
public static void main(String[] args)
{
ActionFrame frame = new ActionFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class ActionFrame extends JFrame
{
public ActionFrame()
{
setTitle("ActionTest");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
//add panel to frame
ActionPanel panel = new ActionPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
class ActionPanel extends JPanel
{
public ActionPanel()
{//定义动作
Action yellowAction = new ColorAction("Yellow",
new ImageIcon("yellow.gif"),
Color.YELLOW);
Action blueAction = new ColorAction("Blue",
new ImageIcon("blue.gif"),
Color.BLUE);
Action redAction = new ColorAction("Red",
new ImageIcon("red.gif"),
Color.RED);
//增加按钮到动作
add(new JButton(yellowAction));
add(new JButton(blueAction));
add(new JButton(redAction));
//将Y、B、R与其名字相对应
InputMap imap = 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 = 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(Action.SHORT_DESCRIPTION,
"set panel color to " + name.toLowerCase());
putValue("color",c);
}
public void actionPerformed(ActionEvent event)
{
Color c = (Color)getValue("color");
setBackground(c);
}
}
}