• java 将动作和名字绑定


    简介

    AbstractAction 抽象动作 将动作和名字绑定

    code

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class ActionFrame extends JFrame {
        private JPanel buttonPanel;
        private static final int DEFAULT_WIDTH = 300;
        private static final int DEFAULT_HEIGHT = 200;
    
        public ActionFrame() {
            setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
            buttonPanel = new JPanel();
    
            // define actions
            Action yellowAction = new ColorAction("Yellow", new ImageIcon("test.gif"), Color.YELLOW);
            Action blueAction = new ColorAction("Blue", new ImageIcon("test.gif"), Color.BLUE);
            Action redAction = new ColorAction("Red", new ImageIcon("test.gif"), Color.RED);
    
            // add buttons for these actions
            buttonPanel.add(new JButton(yellowAction));
            buttonPanel.add(new JButton(blueAction));
            buttonPanel.add(new JButton(redAction));
    
            // add panel to frame
            add(buttonPanel);
    
            // assciate the Y, B, and R keys with names
            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");
    
            // associate the names with actions
            ActionMap amap = buttonPanel.getActionMap();
            amap.put("panel.yellow", yellowAction);
            amap.put("panel.blue", blueAction);
            amap.put("panel.red", redAction);
        }
    
        public class ColorAction extends AbstractAction { // core
            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);
            }
        }
    }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    android使用ant编译打包
    Android OpenGL ES 2.0 (二) 画立方体
    Android OpenGL ES 2.0 (三) 灯光pervertex lighting
    OpenGL ES2.0里的3种变量
    JAVA对DOM的一些解析、修改、新增操作
    webservice(二)示例代码
    linux改IP
    android从未安装的apk文件里获取信息(包信息,资源信息)
    Android OpenGL ES 2.0 (一) 画三角形
    一个关于closure的问题.
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13905836.html
Copyright © 2020-2023  润新知