单击按钮后keylistener无法正常工作 [英] keylistener not working after clicking button

查看:124
本文介绍了单击按钮后keylistener无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中有一个keylistener连接到我的框架,当我按任意键时我可以检测到按键,但是发生了一件奇怪的事情。我的游戏是一个扫雷游戏,我有一个重启按钮,基本上清理板并重新启动它。奇怪的是,当我用鼠标点击按钮时,一切都清理得很好并且电路板被提醒但是keylistener停止工作。更奇怪的是,我有一个jmenuitem基本上自动点击按钮。所以就像restartbutton.doclick()

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

如果我点击jmenuitem重新启动它就会重新启动精确清除所有内容并且keylistener仍然起作用。我甚至可以看到点击按钮。任何想法为什么会发生这种情况?

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?

谢谢

这是附在我的主框架上的。这是在单击按钮后停止工作的监听器。

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


       }

       });


推荐答案

建议:


  • 你的焦点问题是KeyListener停止工作,因为它正在侦听的容器已经失去了对JButton的关注。

  • 一个解决办法是让JButton无法通过调用 setFocusable(false)来获得焦点。

  • 但我建议你不要如果可能的话,根本不使用KeyListener,而是使用键绑定,因为绑定你没有这个问题,而且它是一个更高级别的结构。

  • 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?

最好是通过 Key Bindings教程并实现那里的建议。

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

这篇关于单击按钮后keylistener无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆