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