专注于java applet
我制作了一个完全基于JPanel的java游戏。当我将它添加到 JFrame 时,它工作得很好,当我将它添加到 JApplet 并使用 eclipse 内置的 applet 测试器测试它时,它工作得很好。但是,当我尝试通过 html 站点运行小程序时,它不起作用。它会加载,但不需要键盘输入。我已将其设置为“按 s”开始游戏,但即使我单击游戏并按 s,也没有任何反应。
我是否必须设置键盘焦点,因为我认为这是自动完成的。
I made a java game that is all based on JPanel. When I add it to a JFrame it works perfectly, and when I add it to a JApplet and test it with the built in applet tester of eclipse it works perfectly. However, when I try to run the applet through an html site it doesn't work. It loads, but it doesn't take keyboard input. I have it set up where "pressing s" starts the game, but even when I click on the game and press s, nothing happens.
Do I have to set the keyboard focus, because I thought that was done automatically.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
KeyEvent 仅传递给具有焦点的组件。我猜你的面板没有焦点,所以请确保面板可聚焦,然后在 GUI 可见后使用 requestFocusInWindow() 方法以确保面板具有焦点。
然而,更好的解决方案不是依赖 KeyListener,而是使用 Key Bindings。 Swing 被设计为使用键绑定。
详细了解按键绑定。
KeyEvents are only passed to the component that has focus. I would guess your panel doesn't have focus, so make sure you make the panel focusable and then use the requestFocusInWindow() method once the GUI is visible to make sure the panel has focus.
However, the better solution to the problem is not to rely on the KeyListener but instead to use Key Bindings. Swing was designed to use Key Bindings.
Read more about Key Bindings.