将键绑定添加到JButton,以便从操作命令中获取其操作?

时间:2015-11-09 02:27:48

标签: java swing action keymapping

我在另一个问题中找到了一个很酷的方法来创建一个JButton,其行为以简单的方式编写和查看:

public JButton makeToolbarButton(String title, String actionCommand) {
    JButton button = new JButton(title);
    button.setActionCommand(actionCommand);
    button.addActionListener(this);
    return button;
}

此方法所在的类实现了ActionListener,而按钮命令则由:

指定
public void actionPerformed(ActionEvent e) {
    int action = Integer.parseInt(e.getActionCommand());
    switch(action) {
        case 1:
            System.out.println("This button pressed.");
        break;
    }
}

按钮由:

制作
    JButton button1 = makeToolbarButton("Button 1", "1");

所以我的问题是:我可以通过这种方法将KeyStrokes添加到按钮吗?我试过这样的事情(在makeToolbarButton方法内部):

    button.getInputMap().put(KeyStroke.getKeyStroke("B"), "button_pressed");
    button.getActionMap().put("button_pressed", button.getAction());

但我认为这不起作用,因为动作命令实际上并没有将动作分配给特定按钮。有没有办法在makeToolbarButton()方法中添加一些东西,为KeyStroke添加一个参数来实现这个目的?

1 个答案:

答案 0 :(得分:4)

我认为你忽略了Action API的重点。 Action旨在提供单一的,自包含的工作单元。这意味着actionCommand确实不是必需的,因为当触发actionListener事件时,您确切地知道它被执行的上下文

我也避免使用KeyStroke.getKeyStroke(String),因为文字是对你想要做的事情的详细描述(即pressed B或其他东西,但不用说,这是一个很难做到的事情)

因此,下面演示了如何使用Action并将它们分配给按钮和键绑定

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ActionTest {

    public static void main(String[] args) {
        new ActionTest();
    }

    public ActionTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            add(createButton(new ActionOne(), KeyStroke.getKeyStroke(KeyEvent.VK_1, 0)));
            add(createButton(new ActionTwo(), KeyStroke.getKeyStroke(KeyEvent.VK_2, 0)));
        }

        public JButton createButton(Action action, KeyStroke keyStroke) {
            JButton btn = new JButton(action);
            btn.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "button_pressed");
            btn.getActionMap().put("button_pressed", action);
            return btn;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.dispose();
        }

    }

    public class ActionOne extends AbstractAction {

        public ActionOne() {
            putValue(NAME, "1");
            putValue(Action.ACTION_COMMAND_KEY, "Action.one");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(e.getActionCommand());
        }

    }

    public class ActionTwo extends AbstractAction {

        public ActionTwo() {
            putValue(NAME, "2");
            putValue(Action.ACTION_COMMAND_KEY, "Action.two");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(e.getActionCommand());
        }

    }

}

有关详细信息,请参阅How to Use Actions