简体   繁体   English

KeyListener在Java中不起作用

[英]KeyListener is not working in Java

I want to be able to receive input from the keyboard by the user but I've added everything I thought would allow my program to do this and still it does not work. 我希望能够接收用户从键盘输入的内容,但是我添加了我认为允许程序执行的所有操作,但仍然无法执行。 What am I doing wrong? 我究竟做错了什么?

class KeyInput implements KeyListener {
    public void keyPressed(KeyEvent e) {
        System.out.println("keyPressed");
    }
    public void keyReleased(KeyEvent e) {
        System.out.println("keyReleased");
    }
    public void keyTyped(KeyEvent e) {
        System.out.println("keyTyped");
    }       
}

public GameView() {
    this.addKeyListener(new KeyInput());
}

The constructor works fine and KeyInput is an inner class of the GameView object. 构造函数运行良好,KeyInput是GameView对象的内部类。 When running the game, if I press a key nothing gets printed to the system output. 在运行游戏时,如果按任意键,则什么都不会打印到系统输出。 Am I missing something? 我想念什么吗? Thanks! 谢谢!

KeyListener is fickle mistress, it wants a lot of attention all the time. KeyListener是善变的情妇,它一直都需要很多关注。 Basically, it will only raise key events if the component it is registered to has focus AND is focusable. 基本上,只有注册的组件具有焦点并且可聚焦时,它才会引发关键事件。

Generally, you want to avoid using it and use key bindings API instead, How to Use Key Bindings , but this will depend on whether you MUST use pure AWT APIs or not.... 通常,您要避免使用它,而是改用键绑定API,即“ 如何使用键绑定” ,但这取决于您是否必须使用纯AWT API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM