屏幕上未绘制矩形(Java GUI)

时间:2018-08-16 09:46:32

标签: java user-interface awt bufferstrategy

我目前正在观看RealTutsGML的Java游戏开发教程。在他的教程中,屏幕上绘制了一个黑色的矩形。但是,在完成所有步骤后,我的屏幕上没有绘制黑色矩形。

过去几天,我已经研究了这个问题,但没有找到任何解决方案。

提前谢谢!

public class Game extends Canvas implements Runnable{


    private static final long serialVersionUID = 2368659607588750303L;
    private static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
    private Thread thread;
    private boolean running = false;


    public Game() {
        new Window(WIDTH, HEIGHT, "LETS BUILD A GAME", this);
    }

    public synchronized void start() {
        thread = new Thread(this);
        running = true;
        thread.start();
    }

    public synchronized void stop() {
        try {
            thread.join(); //stops thread
            running = false;
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        //game loop
        long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 1000000000 / amountOfTicks;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0;

        while(running == true) {
            long now = System.nanoTime();
            delta += (now - lastTime) /ns;
            lastTime = now;
            while(delta >= 1) {
                tick();
                delta--;
            }

            if(running == true) 
                render();

            frames++;


            if(System.currentTimeMillis() - timer > 1000) {
                timer += 1000;
                System.out.println("FPS " + frames);
                frames = 0;
            }
        }

        stop();
    }

    private void tick() {

    }
    private void render() {
        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null) {    
            this.createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        g.dispose();
        bs.show();
    }

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

0 个答案:

没有答案