focus for java applets

寵の児 提交于 2019-12-11 03:06:39

问题


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.


回答1:


but it doesn't take keyboard input.

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.



来源:https://stackoverflow.com/questions/4241489/focus-for-java-applets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!