当计时器触发事件时,我的 KeyEvents 不会被注册。如何解决这个问题?
这里是java菜鸟。在我的 Application 类中,我有一个 JPanel,其 focusable 设置为 true,并添加了一个 KeyListener 类。我还注册了一个计时器,并在应用程序的主函数中设置了 TimerListener 类。 KeyEvents 工作,但是一旦我按下 JButton 调用timer.start(),KeyEvents 就会停止触发,并且只有计时器的 actionPerformed 执行。当timer.stop()被调用时,KeyEvents仍然不起作用。我知道我设置错了,但我不知道如何修复它。有人可以帮忙吗?
java noob here. In my Application class, I have a JPanel with focusable set to true and a KeyListener class added to it. I also have a Timer registered with a TimerListener class set up in the Application's main function. The KeyEvents work, but once I press the JButton to call timer.start(), KeyEvents stop firing and only the timer's actionPerformed executes. When timer.stop() gets called, the KeyEvents still don't work. I know I've set this up wrong, but I can't figure out how to fix it. Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
KeyEvent 仅传递给具有焦点的组件。
如果单击该按钮,则该按钮具有焦点,而不是面板。
尝试在按钮 ActionListener 代码中将焦点重置回面板上。
或者更好的解决方案是使用按键绑定。您可以设置键绑定,以便当焦点位于面板或面板上的其他组件上时仍会调用该操作。
KeyEvents are only passed to the component with focus.
If you click on the button, then it has focus, not the panel.
Try resetting focus back on the panel in the button ActionListener code.
Or a better solution is to use Key Bindings. You can set up the key bindings so that the Action will still be invoked when the focus is on the panel or another component on the panel.