Action

来源:互联网 发布:西红门火灾 知乎 编辑:程序博客网 时间:2024/06/04 17:46

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
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 Test
{

 /**
  * @param args
  */
 @SuppressWarnings("unused")
 public static void main(String[] args)
 {
  Color_JFrame cf = new Color_JFrame();

 }

}

class Color_JFrame extends JFrame
{
 private static final long serialVersionUID = 1L;
 JPanel colorJpanel;

 public Color_JFrame()
 {
  colorJpanel = new ActionPanel();
  this.add(colorJpanel);
  this.setSize(Toolkit.getDefaultToolkit().getScreenSize().width / 2,
    Toolkit.getDefaultToolkit().getScreenSize().width / 2);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
 }

}

class ActionPanel extends JPanel
{
 private static final long serialVersionUID = 1L;
 private JButton yButton;
 private JButton bButton;
 private JButton rButton;
 private Action yAction;
 private Action bAction;
 private Action rAction;
 private final static String y = "黄色";
 private final static String r = "红色";
 private final static String b = "黑色";

 private void addAciotn()
 {
  InputMap ip = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
  ip.put(KeyStroke.getKeyStroke("ctrl Y"), y); //得到输入键 将输入键放在y这个字符串内
  ip.put(KeyStroke.getKeyStroke("ctrl R"), r);
  ip.put(KeyStroke.getKeyStroke("ctrl B"), b);
  ActionMap am = getActionMap(); //ActionMap 提供从 Object(称为键 或 Action 名)到 Action 的映射
  am.put(y, yAction);
  am.put(r, rAction);
  am.put(b, bAction);
  yButton.addActionListener(yAction);
  rButton.addActionListener(rAction);
  bButton.addActionListener(bAction);
  Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
  this.setSize(d.width / 2, d.height / 2);
  this.setLayout(new FlowLayout(FlowLayout.LEFT));
  this.add(yButton);
  this.add(rButton);
  this.add(bButton);
 }

 public ActionPanel()
 {
  yButton = new JButton(y);
  bButton = new JButton(b);
  rButton = new JButton(r);
  yAction = new Color_Action(y, Color.YELLOW);
  rAction = new Color_Action(r, Color.RED);
  bAction = new Color_Action(b, Color.BLACK);
  this.addAciotn();
 }

 class Color_Action extends AbstractAction
 {
  private static final long serialVersionUID = 1L;
  private final String color = "color";

  public Color_Action(String ActionName, Color c)
  {
   putValue(Action.NAME, ActionName);
   putValue(color, c);
   putValue(Action.SHORT_DESCRIPTION,
     "this is color Action of" + c.toString());
  }

  @Override
  public void actionPerformed(ActionEvent e)
  {
   Color c = (Color) getValue(color);
   setBackground(c);
  }
 }
}

输入->字符串->Action

0 0
原创粉丝点击