package Chapter8Event; import java.awt.Color; import java.awt.Image; import java.awt.event.ActionEvent; import java.net.URL; 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; /* * ¶à¸ö¶¯×÷´¥·¢Ê¼þ * * Ö÷ÒªÀà»ò½Ó¿Ú£ºAbstractAction£¬KeyStroke£¬InputMap£¬ActionMap * * */ public class ActionFram extends JFrame{ private JPanel buttonPanel; private static int DEFAULT_WIDTH=300; private static int DEFAULT_HEIGHT=200; //Action½Ó¿Ú£º·â×°ÃüÁî,Á¬½Óµ½¶à¸öʼþÔ´¡£Ò»¸ö¶¯×÷ÊÇÒ»¸ö¶ÔÏó£¨ÃüÁîµÄ˵Ã÷£¬Ö´ÐÐÃüÁîÐèÒªµÄ²ÎÊý£ºÀýÈçÀý×ÓÖеÄÐèÒªµÄÑÕÉ«£© //Action½Ó¿ÚÖÐÓÐ8¸ö¸öÔ¤¶¨Ò嶯×÷ //Action½Ó¿ÚÀ©Õ¹ÓÚActionListener½Ó¿Ú //AbstractAction£ºÊµÏÖÁËAction½Ó¿ÚÖгýactionPerformedÍâµÄËùÓз½·¨¡£¶à¸öÏà¹Ø¶¯×÷¿ÉÒÔʹÓÃͬһ¸öÀà //´æ´¢ËùÓеÄÃû/Öµ ¶Ó public ActionFram(){ buttonPanel=new JPanel(); ColorAction ActionYellow=new ColorAction("Yellow", new ImageIcon("yellow.gif"), Color.yellow); ColorAction ActionBlue=new ColorAction("Blue", new ImageIcon("blue.gif"), Color.blue); ColorAction ActionRed=new ColorAction("Red", new ImageIcon("red.gif"), Color.red); createButton(ActionYellow); createButton(ActionBlue); createButton(ActionRed); this.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); this.add(buttonPanel); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); //*****************µÃµ½Í¼Æ¬×ÊÔ´ URL url=this.getClass().getResource("blue.gif"); this.setIconImage(new ImageIcon(url).getImage()); //InputMapÏȽ«°´¼ü¶ÔÏó£¨KeyStroke£©Ó³Éäµ½ÈÎÒâ¶ÔÏóÉÏ //ÔÙÓÉActionMapÀàʵÏÖ½«¶ÔÏóÓ³Éäµ½¶¯×÷Éϵĵڶþ¸öÓ³É䣨ÕâÑùÓ¦¸ÃºÍÊäÈëÓ³ÉäÌõ¼þÓйأ© //WHEN_ANCESTOR_OF_FOCUSED_COMPONENT£ºµ±Õâ¸ö×é¼þ°üº¬ÁËÓµÓмüÅ̽¹µãµÄ×é¼þʱ 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", ActionYellow); amap.put("panel.blue",ActionBlue); amap.put("panel.red",ActionRed); } public void createButton(Action colorAction){ JButton button= new JButton(colorAction); buttonPanel.add(button); } //ÄÚ²¿Àà´¦Àíʼþ 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 e) { Color bg=(Color) getValue("color"); buttonPanel.setBackground(bg); } } public static void main(String[] args) { new ActionFram(); } }