将键绑定添加到JButton,从动作命令获取其操作? [英] Add key bindings to JButtons that get their actions from action commands?

查看:109
本文介绍了将键绑定添加到JButton,从动作命令获取其操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found a cool way in another question to create a JButton whose actions are written and viewed in an easy way:

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

此方法所使用的类实现ActionListener,按钮命令由:

The class this method is in implements ActionListener, and the buttons commands are assigned by:

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 方法内):

So my question is: can I add KeyStrokes to a button by this method? I tried something like this (inside of the makeToolbarButton method):

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

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

But I figure this doesn't work because the action command isn't actually assigning an action to a specific button. Is there a way to add something to the makeToolbarButton() method and a parameter for the KeyStroke to accomplish this?

推荐答案

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

I think you're missing the point of the Action API. A Action is intended to provide a single, self contained, unit of work. This means that the actionCommand really isn't required, as when the actionListener event is triggered, you know exactly the context in which it's been executed

我还避免使用 KeyStroke.getKeyStroke(String),因为文本是你要做什么的详细描述(即按B 或其他什么,但不用说,这是一个很难的正确)

I'd also avoid using KeyStroke.getKeyStroke(String), as the text is a verbose description of what you want to do (ie pressed B or something, but needless to say, it's a pain to get right)

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

So, the following demonstrates how you might use Actions and assign them to a button AND a key binding

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());
        }

    }

}

有关详细信息,请参阅如何使用操作

See How to Use Actions for more details

这篇关于将键绑定添加到JButton,从动作命令获取其操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆