KeyAdapter没有响应〜Java [英] KeyAdapter is not responding ~ Java

查看:89
本文介绍了KeyAdapter没有响应〜Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的突破游戏.但是,KeyAdapter没有收到输入.代码对我来说看起来不错,但也许我缺少一些更基本的东西?

I'm creating a simple breakout game. However, the KeyAdapter isn't receiving the input. The code looks fine to me but maybe I'm missing something more basic?

public DatGamePanel(BustOut bo, long framerate) {

    setBackground(Color.black);
    setPreferredSize( new Dimension(GAME_WIDTH,GAME_HEIGHT));
    setFocusable(true);

    font = new Font("Sans Serif", Font.BOLD, 24);
    fm = this.getFontMetrics(font);

    this.bo = bo;
    period = 1000/framerate;
    bat = new Bat("bat.png",GAME_WIDTH,GAME_HEIGHT-32,2);

    //Get keyboard input :D
    addKeyListener( new KeyAdapter() {
        public void keyPressed(KeyEvent ke) {
            handleInputPressed(ke);
        }

        public void keyReleased(KeyEvent ke) {
            handleInputReleased(ke);
        }
    });
}

public void handleInputPressed(KeyEvent ke) {
    int a = ke.getKeyCode();
    switch(a) {
        case KeyEvent.VK_LEFT:
        bat.keyHandle(0);
        test = 1;
        break;

        case KeyEvent.VK_RIGHT:
        bat.keyHandle(2);
        break;
    }
}

public void handleInputReleased(KeyEvent ke) {
    System.out.println("Key Pressed");
    int a = ke.getKeyCode();
    switch(a) {
        case KeyEvent.VK_LEFT:
        bat.keyHandle(1);
        test = 0;
        break;

        case KeyEvent.VK_RIGHT:
        bat.keyHandle(3);
        break;
    }       
}

这些都是基本的输入句柄.当我按下向左箭头时,测试变量不会改变.怎么了...

These are all the basic input handles. The test variable doesn't change when I push the Left arrow. What's wrong here...

推荐答案

如果您只是在监听几个键,而您在监听的组件可能没有焦点,那么使用键绑定比使用键绑定要好得多. KeyListener.请在此处如何使用键绑定

If you're just listening for a few keys and your component doing the listening may not have the focus, you're far better of using key bindings than a KeyListener. Please look here How to use Key Bindings

如果该建议似乎没有帮助,请考虑创建并发布 SSCCE (请单击链接),一个小的可编译,可运行的程序,该程序演示了解决此问题的最佳方法.然后我们可以检查您的代码,对其进行运行,对其进行修改,并最好地帮助您对其进行修复.

If this recommendation doesn't seem to help, consider creating and posting an SSCCE (please click on the link), a small compilable, runnable program that demonstrates your best attempt at solving this. Then we can inspect your code, run it, modify it and best be able to help you fix it.

这篇关于KeyAdapter没有响应〜Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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