java - Action 和 ActionMap - 向我解释这种行为

标签 java swing jbutton key-bindings abstract-action

我有一个Action

SampleAction a = new SampleAction("foo", null);

然后我将它添加到一个 Button 和一个 ActionMap

JButton b = new JButton(a);
b.getActionMap().put("bar", a);
b.getInputMap().put(KeyStroke.getKeyStroke("F1"), "bar");

我在 Action 中放置了一个跟踪 (System.out.println("Action ["+ e.getActionCommand() + "] performed!");)。当我用鼠标按下按钮时,它显示

Action [foo] performed!

但是当我使用F1时,它显示:

Action [null] performed!

为什么?


class SampleAction extends AbstractAction
{
    public SampleAction(String text, Icon icon) {
        super(text, icon);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Action [" + e.getActionCommand() + "] performed!");
    }
}

最佳答案

除非我误会了你应该调用getActionCommand在你的实例上 JButton通过ae.getSource()你在哪里打电话getActionCommand()ActionEvent 上:

  SampleAction a = new SampleAction("foo", null);

  JButton b = new JButton(a);
  b.getActionMap().put("bar", a);
  b.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F1"), "bar");

class SampleAction extends AbstractAction
{
    public SampleAction(String text, Icon icon) {
    super(text, icon);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("Action [" + ((JButton)e.getSource()).getActionCommand() + "] performed!");
    }
}

更新:

感谢@Kleopatra,这可能是更好的方法:

SampleAction a = new SampleAction("foo", null);

JButton b = new JButton(a);
b.getActionMap().put("bar", a);
b.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F1"), "bar");

 class SampleAction extends AbstractAction {

        public SampleAction(String text, Icon icon) {
            super(text, icon);

            putValue(Action.ACTION_COMMAND_KEY, text);//'foo' will be printed when button clicekd/F1 pressed
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Action [" + e.getActionCommand() + "] performed!");
        }
    }

关于java - Action 和 ActionMap - 向我解释这种行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13741334/

相关文章:

java - 让 ActionListener 在执行整个 ActionListener 之前向 JButton 提交更改

java - 使用 ANT 和 Eclipse 自动创建 JAR

java - 循环文本文件时的额外空间。

java - 覆盖类泛型类型

java - GUI 应用程序允许用户选择绘图的形状和颜色

java - 使用 Eclipse 中的按钮关闭 JFrame

java - 将程序转换为小程序

java - GridBagLayout:gridwidth > 1 时的对齐方式和宽度

java - 从 jtable 更新 jtextfield

java - 更改 jButtons 的功能是不是糟糕的设计?