In my MainWindow class (a JFrame), I use the "+" and "-" keys as hotkeys to modify the value of a certain JTextField called degreeField up or down. I add a KeyEventDispatcher with the following dispatchKeyEventMethod to my KeyboardFocusManger:
@Override
public boolean dispatchKeyEvent(KeyEvent evt) {
if(simPanel.main.isFocused()){
int type = evt.getID();
if(type == KeyEvent.KEY_PRESSED){
int keyCode = evt.getKeyCode();
switch(keyCode){
// other cases
case KeyEvent.VK_PLUS:
// increase degreeField by 1, if double
// otherwise set it to "270.0"
return true;
case KeyEvent.VK_MINUS:
// decrease degreeField by 1, if double
// otherwise set it to "270.0"
return true;
default:
return false;
}
}
else if(type == KeyEvent.KEY_RELEASED){
// irrelevant
return false;
}
}
return false;
}
The KeyEventDispatcher works and degreeField's text is modified as expected. However, when I have another JTextField focused, the "+" or "-" is also entered into that field.
Since I return true, I was under the impression that the event should no longer be dispatched by the JTextField I have focused. Using the NetBeans debugger, I put a break point into the relevant case and checked the text of the focused text field. At the time, there was no + appended. The + is therefore appended after I finish dispatching this event and return true.
Anyone got any ideas, how I can actually prevent the event from being passed down further?
I know I could put an extra listener on the text field to prevent "+" and "-" chars from being entered, but I would prefer a solution that works for non-char keys as well. (I have a similar problem with up and down arrow keys; it doesn't break anything, just annoyingly cycles through my text fields).
Thanks to MadProgrammer for this:
InputMap im = senderXField.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = senderXField.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, 0), "Pressed.+");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Pressed.up");
am.put("Pressed.+", angleUpAction); // works fine
Sadly
am.put("Pressed.up", indexUpAction); // does not trigger
This applies to all arrow keys. They do their usual thing (move cursor or focus respectively) and don't trigger the actions. If I use the WHEN_FOCUSED InputMap, they work as intended, leading me to believe that their default behavior is implemented as a KeyBinding at the WHEN_FOCUSED level that can be overwritten.
While, technically, as a workaround, I could implement the arrow key commands for all text fields in my MainWindow, that would be ... weird. I hope there's a better solution that let's me keep the command for the entire window but also overwrite their default behaviour.
Solved