Java:KeyListener不起作用:找不到符号

时间:2014-05-05 16:13:43

标签: java keyboard awt keylistener keyevent

我试图用键盘移动砖块。经过几个小时的网络搜索,我找不到错误。互联网上的每个教程都与我尝试的方式完全相同,但它不会起作用。它只是说它在addKeyListener(this)中找不到方法。有人能帮我吗?这是我的代码:

import java.util.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Game implements KeyListener
{
    private L_Brick lBrick; //first kind of brick
    private Q_Brick qBrick; //second kind of brick
    private List<Boolean> brickList;

    public Game()
    {
        brickList = new ArrayList<Boolean>();
        brickList(true);
        brickList(false);
        addKeyListener(this); //here it says cannot find symbol
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }

    public void play()
    {
        Collections.shuffle(brickList);
        if(brickList(0) == true)
        {
            lBrick = new L_Brick();
            lBrick.moveDown();
        } else {
            qBrick = new Q_Brick();
            qBrick.moveDown();
        }
    }

    public void keyPressed(KeyEvent e)
    {
        int keys = e.getKeyCode();
        if(keys == KeyEvent.VK_A)
        {
            System.out.println("works");
        }
    }

    public void keyReleased(KeyEvent e)
    {
    }

    public void keyTyped(KeyEvent e)
    {
    }
}

1 个答案:

答案 0 :(得分:0)

您的类不是组件和键侦听器可以添加到JComponent(您只能实现KeyListener)。再次查看示例它应该扩展JComponent(如JPanel)