Reputation: 572
I have a JPanel with lots of components in it. When the user presses "a", I want to do something and consume the "a", EXCEPT if the user is in a textbox (or other part of the screen that accepts "a")--in that case, I don't want to know about the "a".
In the code below, I get notified of the "a", even if the focus is on a text box (typing "a" while in the textbox puts the "a" in the textbox and also notifies me about the "a").
JComponent jc = the panel...;
InputMap inputMap = jc.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap actionMap = jc.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "qcAccept");
actionMap.put("qcAccept", new AbstractAction("qcAccept") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("A pressed, " + e);
}
});
Upvotes: 3
Views: 2204
Reputation: 324098
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "qcAccept");
You are listening for the keyPressed event. Text components listen for the keyTyped event. So that is why both bindings are still working. Try:
inputMap.put(KeyStroke.getKeyStroke("typed a"), "qcAccept");
Upvotes: 2