I have a keylistener attached to my frame in java, i can detect key presses when I hit any key, a strange thing is happening however. My game is a minesweeper game, I have a restart button that basically clears the board and remines it. The weird thing is when I click the button with the mouse everything clears fine and the board is remined but the keylistener stops working. Even stranger I have a jmenuitem that basically does a automated click of the button. So its like restartbutton.doclick()
if i click the jmenuitem to restart it restarts fine clears everything and the keylistener still functions. I can even see the button being clicked. Any ideas why this could be happening?
Thanks
this is attached to my main frame. this is the listener that stops working after clicking the 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){
}
});
A Simple KeyListener Java Class Create a new KeyListener object. Override the methods that correspond to the key events you want to monitor e.g keyPressed , keyReleased , keyTyped . Create a JTextField component. Use it's addKeyListener method to add to it the KeyListener you've created.
keyPressed is fired whenever any key press occurs. keyTyped is fired when a key is pressed that can be converted into a unicode character.
The listener interface for receiving keyboard events (keystrokes). The class that is interested in processing a keyboard event either implements this interface (and all the methods it contains) or extends the abstract KeyAdapter class (overriding only the methods of interest).
Suggestions:
setFocusable(false)
on it.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.
this is focus problem, you can use this code to give focus again
getTopLevelAncestor().requestFocus();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With