Search code examples
javaswingkeylistenerkeyevent

KeyPressed event not happening?


this code builds correctly and everything appears to work but the key do nothing. I think it's either the action listener or the oval is not updating. I am trying to work through a beginners java game programming. I am sure it's something easy but I am not catching it. I am on a mac in sublime text 2 if that makes a difference.

package javagame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JavaGame extends JFrame {

int x, y;

public class AL extends KeyAdapter {

    public void keyPressed(KeyEvent e) {
        int keycode = e.getKeyCode();
        if(keycode == e.VK_LEFT); {
            x-= 3;
        }
        if(keycode == e.VK_RIGHT); {
            x+= 3;
        }
        if(keycode == e.VK_UP); {
            y-= 3;
        }
        if(keycode == e.VK_DOWN); {
            y+= 3;
        }
    }


    public void keyReleased(KeyEvent e) {

    }
}

public JavaGame() {
    addKeyListener(new AL());
    setTitle("Jave Game");
    setSize(700, 700);
    setResizable(false);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x = 350;
    y = 350;
}

public void paint(Graphics g) {
    g.fillOval(x, y, 15, 15);

    repaint();
}

public static void main(String[] args) {
    new JavaGame();
}

}

Solution

  • You need to remove the semi-colons from your if statements:

    if (keycode == e.VK_LEFT)
    {
       x-= 3;
    }
    

    Currently the code blocks that follow your if statements are rendered free standing as the semi-colons terminate those statements.


    Some Swing-specific notes:

    • It's better to use paintComponent from a sub-classed JComponent for better paint performance.
    • Use Key bindings over KeyListener for improved key event management. Here is an example.