Keylistener does not work after clicking a button

I have a keylistener attached to my frame in java, I can detect keystrokes when I press any key, however a strange thing happens. My game is a minesweeper, I have a restart button that basically clears the board and overwrites it. Strange, when I press the button with the mouse, everything clears up fine, and the board remains in memory, but the keylistener stops working. Even a stranger, I have a jmenuitem that basically does an automatic button click. So this is like restartbutton.doclick ()

if I click on jmenuitem to restart it, reboots, clears everything, and the keylistener function still functions. I can even see that a button is pressed. Any ideas why this could be happening?

thanks

this is attached to my main frame. This is a listener that stops working after clicking a button.

frame.addKeyListener(new KeyListener(){ public void keyReleased(KeyEvent e){ } public void keyPressed(KeyEvent e){ System.out.println("hey"); int keycode = e.getKeyCode(); if(e.isControlDown() & keycode==KeyEvent.VK_C){ balh blah balh } } public void keyTyped(KeyEvent e){ } }); 
+6
source share
4 answers

Suggestions:

  • Your focus problem is when the KeyListener stops working because the container it is listening to has lost focus on JButton.
  • One solution is to prevent JButton from getting focus by calling setFocusable(false) on it.
  • But I recommend that you do not use KeyListener at all, if possible, but rather key bindings, since you do not have this problem with bindings, and is also a higher-level construct.

Edit
Regarding

what would be the best way to change this to key binding?

It’s best to go through the keyword tutorial and follow the recommendations found there.

+11
source

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

getTopLevelAncestor().requestFocus();

+1
source

Based on the answer to this similar question , I applied KeyEventDispatcher instead of using default listeners. I believe that this feature will be quite global, so you may need to check and make sure that the right things are visible / focused.

  KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED) { System.out.println("tester"); } return false; } 
0
source

I managed to solve this problem by setting the container container true for the setFocused property:

 frame.setFocusable(true); 
0
source

Source: https://habr.com/ru/post/901173/


All Articles