Reputation: 78
I'm writing an application in Java where I need one thing to happen when the user presses letter keys and something different when the user hits ENTER but I can't seem to get a key name when I hit ENTER, only a new line.
I think I should be using getKeyStroke but I'm not sure if that's possible because I'm using ActionEvent.
This is what I'm doing so far:
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);
Then I have a separate class with the Action.
class AnAction extends AbstractAction{
public void actionPerformed(ActionEvent e) {
System.out.println("Received: " + e.getActionCommand());
}
}
When I type two series of "a" then "b" then "c" then "ENTER" this is what my output looks like:
Received: a
Received: b
Received: c
Received:
Received: a
Received: b
Received: c
Received:
Upvotes: 1
Views: 2136
Reputation: 1
Try this:
panelMaster.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke( "pressed ENTER" ), "doSomething");
panelMaster.getActionMap().put("doSomething", anAction);
Upvotes: 0