我正在用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”然后“输入”这就是我的输出:
Received: a
Received: b
Received: c
Received:
Received: a
Received: b
Received: c
Received:
答案 0 :(得分:0)
你可以使用 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)
答案 1 :(得分:0)
试试这个:
panelMaster.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke( "pressed ENTER" ), "doSomething");
panelMaster.getActionMap().put("doSomething", anAction);