事件处理与击键的关联——事件处理

下面是将按钮和按键映射到不同动作对象上的实例程序。

package action;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ActionFrame extends JFrame {
    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        ActionFrame actionFrame = new ActionFrame();
        actionFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        actionFrame.setVisible(true);
    }

    private JPanel buttonPanel;
    private static final int DEFAULT_WIDTH = 500;
    private static final int DEFAULT_HEIGHT = 300;
    public ActionFrame() {
        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{
        private static final long serialVersionUID = 1L;

        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");
            buttonPanel.setBackground(c);
        }
    }
}
  • void putValue(String key, Object value)
    将名/值放置在动作对象内
    key :用动作对象存储的名字。
    value :与名字关联的对象
  • Object getValue(String key)
    返回被储存动作对象的值
  • static KeyStroke getKeyStroke(String description)
    根据便于阅读的说明创建一个按键(由空格分隔的字符串序列) 例如,ctrl r
  • ActionMap getActionMap()
    返回关联动作键和动作对象的映射
  • InputMap getInputMap(int flag)
    获得将按键映射到动作键的输入映射

学习Java核心技术卷一第八章第二节

发布了176 篇原创文章 · 获赞 46 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43207025/article/details/104189692