Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

java - keylistener not working after clicking button

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){


       }

       });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...