jym338
jym338

Reputation: 1

Error using keyAdapter and keyEvent in java

I'm a beginner in programming and I have been working on a small project, the well known game called Tetris and I came upon this little problem and I would like you to help me with a solution. I imported : import java.awt.event.KeyAdapter and import java.awt.event.KeyEvent to be able to use my keyboard to play the game, but when I'm extending the class that I created to use the keys, it showing me an error!!

Here is the code:

addKeyListener(new TAdapter()); 

The error happens here saying this:

The method addKeyListener(keyListener) in the type Component is not applicable for the arguments(Board.TAdapter)

class TAdapter extends keyAdapter { // The second happens here: keyAdapter cannot be //resolved to a type public void keyPressed(keyEvent e) { // The third happens here: keyEvent //cannot be resolved to a type

        if (!isStarted || curPiece.getShape() == Tetrominoes.NoShape) {
            return;

        }

        int keycode = e.getKeyCode();

        if (keycode == 'p' || keycode == 'P') {
            pause();
            return;

        }
        if (isPaused)
        {return;}

    switch (keycode) {
        case KeyEvent.VK_LEFT:
            tryMove(curPiece, curX - 1, curY);
            break;
        case KeyEvent.VK_RIGHT:
            tryMove(curPiece, curX + 1, curY);
            break;
        case KeyEvent.VK_DOWN:
            tryMove(curPiece.rotateRight(), curX, curY);
            break;
        case KeyEvent.VK_UP:
            tryMove(curPiece.rotateLeft(), curX, curY);
            break;
        case KeyEvent.VK_SPACE:
            dropDown();
            break;
        case 'd': 
            oneLineDown();
            break;
        case 'D':
            oneLineDown();
            break;

    }
  }

Upvotes: 0

Views: 1870

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347214

You should avoid KeyListeners, they have a number of issues related to focus, they can also bloat your code and make the management more difficult.

You should instead, take advantage of the Key Bindings API, which provide a more reusable API and provide the means to determine the level of focus a component needs in order to recieve key events

Upvotes: 2

M A
M A

Reputation: 72854

Use KeyAdapter instead of keyAdapter, and KeyEvent instead of keyEvent. The class names are case sensitive.

class TAdapter extends KeyAdapter 

Upvotes: 0

Related Questions