当计时器触发事件​​时,我的 KeyEvents 不会被注册。如何解决这个问题?

发布于 2024-09-24 21:53:04 字数 285 浏览 0 评论 0原文

这里是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

童话 2024-10-01 21:53:04

但是一旦我按下 JButton 来呼叫
timer.start(),KeyEvents 停止触发
并且仅执行计时器的操作
执行。

KeyEvent 仅传递给具有焦点的组件。

如果单击该按钮,则该按钮具有焦点,而不是面板。

尝试在按钮 ActionListener 代码中将焦点重置回面板上。

或者更好的解决方案是使用按键绑定。您可以设置键绑定,以便当焦点位于面板或面板上的其他组件上时仍会调用该操作。

but once I press the JButton to call
timer.start(), KeyEvents stop firing
and only the timer's actionPerformed
executes.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文