the fool
the fool

Reputation: 19

Game Loop not Running

I am making a space shooter game in java. I am using the Runnable interface, meaning that the run() method should automatically be called. Inside the method, I have a loop that keeps on running until someone sets the boolean running to false. The loop should be printing working, but it is not doing so. Here is my code:

package main;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JPanel implements Runnable {

    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    public static final String TITLE = "Space Shooter";

    private boolean running = false;
    private Thread thread;


    public Game() {

    }

    private synchronized void start() {
        if (running)
            return;

        running = true;
        thread = new Thread();
        thread.start();
    }

    private synchronized void stop() {
        if (!running)
            return;

        running = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.exit(1);
    }

    @Override
    public void run() {
        while (running) {
            System.out.println("WORKING");
        }
        stop();
    }

    public static void main(String[] args) {

        Game game = new Game();
        JFrame frame = new JFrame(TITLE);

        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(game);
        frame.setVisible(true); 

        game.start();

    }

}

Upvotes: 0

Views: 234

Answers (1)

wero
wero

Reputation: 32980

You forgot to pass the Runnable instance to the thread constructor:

 thread = new Thread(this);

Upvotes: 2

Related Questions