addKeyListener 未按预期工作
我使用按键事件而不是按键绑定,因为我还不了解按键绑定。
我用带有 Jbutton 的 JPanel
制作了 JFrame
。
我将 JPanel
实例化为框架类中的面板,将 JButton
实例化为面板类中的按钮。我继续编辑面板的类。
如果我 addKeyListener
带有一个新的 keyAdapter
,它只打印“按键按下”,那么如果我输入任何内容,什么也不会发生。但是,如果我使用相同的通用 keyAdapter
执行 button.addKeyListener
,则当我按下某个键时,将打印“key Pressed”。
我认为这与实例有关。所以我的第一个问题是:如何让组件向自身添加关键侦听器和/或为什么不调用 addKeyListener
甚至 this.addKeyListener
执行此操作?
当我添加一个关键侦听器时,代码会继续运行(可能应该如此),因此我尝试执行 while(some boolean) thread.sleep(1000)
只是让关键侦听器在按键时更改布尔值按下。我只是想让我的代码等待,直到按下一个键。我知道这没什么可继续的,但我的问题是:是否有更好或更干净的方法来暂停方法/等待输入?
I'm using Key Events over Key Binding because I don't understand key binding yet.
I make a JFrame
with a JPanel
with a Jbutton.
I instance the JPanel
as panel in the frame's class and the JButton
as button in the panel's class. I continue editing the panel's class.
If I addKeyListener
with a new keyAdapter
that just prints "key pressed", nothing happens if I type anything. BUT if I do button.addKeyListener
with the same generic keyAdapter
, "key pressed" will print when I push a key.
I assume this has something to do with instances. So my first question is: How can I have a component add a key listener to itself and/or why doesn't calling the addKeyListener
or even this.addKeyListener
do this?
When I add a key listener the code keeps going (as it probably should) so I tried doing while(some boolean) thread.sleep(1000)
just having the key listener change the boolean when a key is pressed. I simply want my code to wait until a key is pressed. I understand this isn't much to go on but my question is: is there a better or cleaner way to pause methods/wait for input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能是因为组件没有焦点。 KeyEvent 只分派给具有焦点的组件。对于按键绑定来说这不是问题,因为即使组件没有焦点,它们也可以处理事件。
Probably because the comonent doesn't have focus. KeyEvents are only dispatched to the component with focus. This is not a problem with Key Bindings because they can handle events even when the component doesn't have focus.