keylistener not working after clicking button

Solution 1:

Suggestions:

  • Yours is a focus issue, where the KeyListener stops working because the container it is listening to has lost focus to the JButton.
  • One solution is to make the JButton not able to gain focus by calling setFocusable(false) on it.
  • But I recommend that you don't use a KeyListener at all if possible, but rather key bindings, since with bindings you don't have this issue and also it is a higher level construct.

Edit
Regarding:

what would be the best way to change that to a key binding?

Best would be to go through the Key Bindings tutorial and to implement the recommendations found there.

Solution 2:

this is focus problem, you can use this code to give focus again

getTopLevelAncestor().requestFocus();