Search code examples
javakeypresskeylistenerjappletkeyevent

Java keyPressed() method only works after player presses tab


I am making a little game applet, and I have gotten to where the player should move around with the controls.

Main:

public class Main extends JApplet implements Runnable, KeyListener {
    private static final long serialVersionUID = 1L;
    private static DoubleBufferedCanvas canvas = new DoubleBufferedCanvas();
    public static int width = 900;
    public static int height = 600;
    public static int fps = 60;

    public static Ailoid ailoid = new Ailoid();
    public static Player player = new Player();

    // Initialize
    public void init() {
        setSize(width, height);
        setBackground(Color.white);
        add(canvas);
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);

        ailoid.setLocation(new Location(100, 100));
        AlienManager.registerAlien(ailoid);
        player.setLocation(new Location(400, 400));
    }

    // Paint graphics
    public void paint(Graphics g) {
        super.paint(g);
    }

    // Thread start
    @Override
    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }
    // Thread stop
    @Override
    public void destroy() {

    }

    // Thread run
    @Override
    public void run() {
        Thread thread = new Thread(this);
        while (thread != null) {
            Updater.run();
            canvas.repaint();
            try {
                // 1000 divided by fps to get frames per second
                Thread.sleep(1000 / fps);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void keyPressed(KeyEvent evt) {
        KeyPress.run(evt);
        System.out.println("DEBUG");
    }

    @Override
    public void keyReleased(KeyEvent evt) {

    }

    @Override
    public void keyTyped(KeyEvent evt) {

    }
}

What happens is that it only starts saying "debug" after I press tab. How would I make it work even if the player doesn't press tab before?


Solution

  • Your Applet most likely does not have the input focus.Try adding

    this.requestFocus ()
    

    to your init method.

    Also note that a JApplet is a part of the Swing framework and thus not threadsafe as mentioned in the documentation