Question

I tried the usual way to handle keypress: implements KeyListener and override keyPressed(). But there are many swing components, and if Im on a combobox, the combobox "thinks" the key is for him. I want to the main app capture the keypress, how to?

Was it helpful?

Solution

You are looking for this Key Bindings

OTHER TIPS

You could use:

KeyEventPostProcessor kepp = new KeyEventPostProcessor() {
  @Override 
  boolean postProcessKeyEvent(KeyEvent e) {
     // handle key event globally
  }
};

KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.addKeyEventPostProcessor(kepp);

This is way harder than you'd think. For example, here's the effort you have to put in to get this working on a Panel with a JFileChooser in it. That's a similar question I asked in the past. I think that will help you solve your problem. You should read both answers given as they're both valid.

To summarize, you've gotta iterate all the InputMaps and the parents of the InputMaps and clear out the keys you want to globally use. Then apply your action to the KeyMap.

You'll need this:

private static void clearInputMap(InputMap inputMap) {
    inputMap.clear();
    while ((inputMap = inputMap.getParent()) != null) {
        inputMap.clear();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top