游戏循环未运行

时间:2016-01-28 00:49:02

标签: java loops

我正在用java制作太空射击游戏。我正在使用Runnable接口,这意味着应该自动调用run()方法。在方法内部,我有一个循环继续运行,直到有人将布尔值running设置为false。循环应该是打印工作,但它没有这样做。这是我的代码:

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();

    }

}

1 个答案:

答案 0 :(得分:2)

您忘记将Runnable实例传递给线程构造函数:

 thread = new Thread(this);