Java使用Action接口

来源:互联网 发布:自学日语软件下载 编辑:程序博客网 时间:2024/05/16 19:35

Swing提供了一种非常时用的机制来封装命令,并将他们链接到多个事件源--Action接口。

下面举例将按钮和击键动作映射到动作对象。点击或者按下Ctrl+B,Ctrl+R,Ctrl+Y改变背景颜色。

package com.Project_Button2;import java.awt.Color;import java.awt.Component;import java.awt.event.ActionEvent;import javax.swing.AbstractAction;import javax.swing.Action;import javax.swing.ActionMap;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.InputMap;import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.KeyStroke;public class ActionFrame extends JFrame{public ActionFrame(){this.setTitle("ActionTest");this.setSize(400, 4000);buttonpanel=new JPanel();//define actionsAction 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);//add buttons for these actionsbuttonpanel.add(new JButton(yellowAction));buttonpanel.add(new JButton(blueAction));buttonpanel.add(new JButton(redAction));//add panel to framethis.add(buttonpanel);//associate the y,b ,and r keys with namesInputMap imp=buttonpanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);imp.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");imp.put(KeyStroke.getKeyStroke("ctrl B"), "panel.bule");imp.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");//映射事件ActionMap amap=buttonpanel.getActionMap();amap.put("panel.yellow", yellowAction);amap.put("panel.bule", blueAction);amap.put("panel.red", redAction);}public class ColorAction extends AbstractAction{public ColorAction(String name,Icon icon,Color color ) {// TODO Auto-generated constructor stubthis.putValue(Action.NAME, name);this.putValue(Action.SMALL_ICON,icon);this.putValue("color", color);this.putValue(Action.SHORT_DESCRIPTION,"Set panel color to "+name.toLowerCase());}@Overridepublic void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stubColor c=(Color) this.getValue("color");buttonpanel.setBackground(c);}}private JPanel buttonpanel;}
运行入口:

package com.Project_Button2;import java.awt.EventQueue;import javax.swing.JFrame;public class StartMain {public static void main(String[] args) {// TODO Auto-generated method stubEventQueue.invokeLater(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubActionFrame a=new ActionFrame();a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);a.setVisible(true);}});}}


0 0