Search code examples
javaoverridingkeyevent

KeyAdapter and KeyEvent is not working in Java, what to do?


So I was trying to make a snake game using the help of BroCode, a youtube channel. I copied the exact same code first to learn but the getkeycode is not working. Means I am pressing the left, right, up, down key but the snake isn't moving. The move function is the same as the video. Here is the move function-

public void move() {
        for(int i=bp; i>0; i--) { //bp means snake body parts
            x[i] = x[i-1];
            y[i] = y[i-1];
        }
        
        switch(dir) {
        case 'U':
            y[0] = y[0]-us;
            break;
        case 'D':
            y[0] = y[0]+us;
            break;
        case 'L':
            x[0] = x[0]-us;
            break;
        case 'R':
            x[0] = x[0]+us;
            break;
        }
    }

Another problem is in the video, after making an inner class extending KeyAdapter, an @Override is there before the keypressed method, but when I try to use it, it gives me an error, the error only goes away when I remove the @Override. I checked on internet that whenever someone use this getkeycode or keyevent methods, there is always the @Override in there. This code is from the internet that I checked, here they used @Override and there is no error-

@Override
public void keyPressed(KeyEvent e)
{
  if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
  {
    e.consume();
  }
}

So is that the real problem? Is that why the snake isn't moving? My code where I tried to get the keypressed is shown below- Code

public class MyKeyAdapter extends KeyAdapter{

        public void keypressed(KeyEvent e) {
            switch(e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                if(dir != 'R') {
                dir = 'L';
                break;}
            case KeyEvent.VK_RIGHT:
                if(dir != 'L') {
                dir = 'R';
                break;}
            case KeyEvent.VK_UP:
                if(dir != 'D') {
                dir = 'U';
                break;}
            case KeyEvent.VK_DOWN:
                if(dir != 'U') {
                dir = 'D';
                break;}
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        if(running) {
            move();
            checkApple();
            checkCol();
        }
        repaint();
    }

This project is so important to me, I have to do this one. Can somebody help me please? I really don't understand why the snake isn't moving when I pressed the key. I tried it with WASD keys too, still it didn't work.


Solution

  • You put a } wrong.

     WRONG: case KeyEvent.VK_LEFT:
                    if(dir != 'R') {
                    dir = 'L';
                    break;}
    
      RIGHT  case KeyEvent.VK_LEFT:
                    if(dir != 'R') {
                    dir = 'L';
                    }
                    break;