gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:20:50 24 4
gpt4 key购买 nike

我有一个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com