问题描述
我有一个类实现 KeyListener
,所有的工作正常,但有一个问题,我的 KeyListener
只有在我点击一个画布,所以如果我开始一个游戏,我必须点击一次,然后我可以使用我的键盘,代码:
public class Game extends Canvas implements Runnable {
$有没有一个方法,使我的画布活动创建后?
....
initGame(){
...
addKeyListener(new Keyboard());
setFocusable(true);
}
private class Keyboard implements KeyListener {
...
}
}
解决方案
KeyListener
只会在其注册的组件可聚焦且具有焦点时响应键事件。
虽然您可以使用
requestFocusInWindow
,但不能保证焦点会被传输到组件,并且如果焦点由于某种原因丢失(您点击另一个组件)
更好的解决方案是使用
JComoponet
基础组件$ c> JPanel ),并使用 API,可让您定义触发关键事件的焦点级别I have a class which implements
KeyListener
, all's working fine, but there a little problem that myKeyListener
works only after I click on a Canvas, so if I start a game, I have to click once on it and then I can use my keyboard, code:public class Game extends Canvas implements Runnable { .... initGame() { ... addKeyListener(new Keyboard()); setFocusable(true); } private class Keyboard implements KeyListener { ... } }
-is there a method which make my canvas "active" after creating?
解决方案
KeyListener
will only respond to key events when the component it is registered to is focusable AND has focus.While you can use
requestFocusInWindow
, there is no guarantee that focus will be transferred to the component and if focus is lost for some reason (you click on another component), then you back to square one.A better solution is to use a
JComoponet
based componet (likeJPanel
) and make use of the Key Bindings API which allows you to define the focus level that triggers the key events这篇关于KeyListener只有在点击画布后才有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-12 03:10