2

我有一个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");

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

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!");
    }
}
4

2 回答 2

3

除非我误解你应该调用你的getActionCommand实例,因为你正在调用:JButtonae.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!");
        }
    }
于 2012-12-06T10:23:37.663 回答
1

我无法访问您的SampleAction,但我猜您在构造函数中传递的“foo”文本用作文本,与操作命令无关。

如果您查看扩展的AbstractButtonJButton,您会看到

public String getActionCommand() {
    String ac = getModel().getActionCommand();
    if(ac == null) {
        ac = getText();
    }
    return ac;
}

ActionEvent在创建传递给动作的哪个时使用此方法。当您单击按钮时,将调用此方法,我假设acnull,但该getText()方法返回"foo"您在SampleAction类中使用的方法。

当您通过按 F1 直接触发动作时,您绕过此机制并简单地触发动作。如果你想避免这种情况,你可以在其中简单地添加一个Action,这ActionMap是对按钮执行“单击”的 API 调用JButtonJButton#doClick

于 2012-12-06T10:31:16.920 回答