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