我正在用Java编写一个应用程序,其中当用户按字母键时需要发生一件事,当用户按ENTER键时需要做一些不同的事情,但当我按ENTER键时似乎无法获得键名,只能换一行。
我认为我应该使用getKeyStroke,但我不确定这是否可能,因为我使用的是ActionEvent。
这就是我到目前为止所做的:
panelMaster.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("A"), "doSomething");
panelMaster.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("B"), "doSomething");
panelMaster.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("C"), "doSomething");
panelMaster.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke( "ENTER" ), "doSomething");
panelMaster.getActionMap().put("doSomething", anAction);然后我有一个单独的Action类。
class AnAction extends AbstractAction{
public void actionPerformed(ActionEvent e) {
System.out.println("Received: " + e.getActionCommand());
}
}当我输入两个序列"a“,然后是"b”,然后是"c“,然后是"ENTER”,我的输出是这样的:
Received: a
Received: b
Received: c
Received:
Received: a
Received: b
Received: c
Received: 发布于 2015-02-10 01:45:36
可以使用KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)
发布于 2016-08-09 00:54:27
试试这个:
panelMaster.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke( "pressed ENTER" ), "doSomething");
panelMaster.getActionMap().put("doSomething", anAction);https://stackoverflow.com/questions/28415655
复制相似问题