Java – keylistener does not work properly after clicking the button
I have a keylistener attached to my framework in Java. I can detect the key when the key is pressed, but strange things are happening My game is a mine sweeping game. I have a restart button, basically clean the board and readjust it Strangely, when I clicked the button with the mouse, everything was clear and the circuit board was restarted, but the keylistener stopped working What's more strange is that I have a jmenuitem that basically clicks the button automatically So it's like restart button doclick()
If I click jmenuite to restart it, restart fine clear everything, and keylistener still works I can even see the click button Any idea why this happens?
thank you
This is attached to my main frame This is the listener that stops working when the button is clicked
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){ } });
Solution
Recommendations:
>Your focus, keylistener, stops working because the container it is listening to has lost its focus on JButton. > One solution is to make JButton unable to get focus by calling setfocusable (false). > But I suggest you use key binding instead of keylistener as much as possible, because you don't have this problem with binding, and it is a higher-level structure
Edit about:
It is best to use key bindings tutorial and implement the recommendations found there