KeyListener只有在点击画布后才有效 [英] KeyListener active only after click on canvas

查看:259
本文介绍了KeyListener只有在点击画布后才有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类实现 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 my KeyListener 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 (like JPanel) and make use of the Key Bindings API which allows you to define the focus level that triggers the key events

这篇关于KeyListener只有在点击画布后才有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆