KeyListener在Java中不起作用 [英] KeyListener is not working in Java

查看:289
本文介绍了KeyListener在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());
}

构造函数工作正常,KeyInput是GameView对象的内部类. 在运行游戏时,如果按任意键,则不会输出任何内容到系统输出. 我想念什么吗?谢谢!

The constructor works fine and KeyInput is an inner class of the GameView object. When running the game, if I press a key nothing gets printed to the system output. Am I missing something? Thanks!

推荐答案

KeyListener是善变的情妇,它一直都需要很多关注.基本上,只有注册的组件具有焦点并且可聚焦时,它才会引发关键事件.

KeyListener is fickle mistress, it wants a lot of attention all the time. Basically, it will only raise key events if the component it is registered to has focus AND is focusable.

通常,您要避免使用它,而改用键绑定API,如何使用键绑定,但这取决于您是否必须使用纯AWT API....

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....

这篇关于KeyListener在Java中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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