Question

I'm trying to use the keyboard to move bricks. After hours of web searching I cannot find the mistake. Every tutorial on the internet does it exactly the same way that I try to but it won't work. It only says that it cannot find the method in addKeyListener(this). Can someone help me? Here's my code:

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)
    {
    }
}
Was it helpful?

Solution

Your class is not in a JComponent and key listeners can be only added to JComponent (You only implemented KeyListener). See the examples again, it should extend a JComponent (like JPanel)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top