1

I try to add a KeyListener to a JFrame. This works fine like this.

JFrame frame = new JFrame();
[...]
frame.addKeyListener(new KeyListener() { [...] });

However, when I have the focus on a button or on a JTextField (like when I click on it), that KeyListener won't react to my button pushes.

Do you know how to fix this?

1 Answer 1

3

Do you know how to fix this?

Yes, use Key Bindings and not a KeyListener. The bindings can be set to work even if the bound component doesn't have the focus, one of their key advantages (no pun intended). The tutorial can be found here: Key Bindings Tutorial.

Note that when you get the InputMap from your bound component, be sure to use the right condition, i.e.,

InputMap inputMap = myComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

There are three input maps for each component, and the one above will be active when the component is held in a top-level window (such as a JFrame) that is currently active. This means that the binding will work even if the component itself doesn't have focus.


You can find some of my sample programs that use Key Bindings, often in conjunction with Swing animation, here:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.