setColor Java无法正常工作

时间:2016-06-16 12:18:39

标签: java

我正在关注一个简​​单的游戏引擎的教程,由于某些原因,当我尝试填充矩形时,setColor不起作用。我只是得到一个空白的白色屏幕。我看过其他类似的帖子,但没有一个似乎能帮助我。这是代码:

package com.binaryscythe.SA.main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

/**
* @author 4nd3r
*
*/
public class Game extends Canvas implements Runnable {
    private static final long serialVersionUID = -3472639816592189040L;

    public static final int WIDTH = 1920, HEIGHT = WIDTH / 16 * 9;  
    private Thread thread;
    private boolean running = false;

    private Handler handler;

    public Game() {
        new Window(WIDTH, HEIGHT, "Senum's Adventure", this);
        handler = new Handler();
    }

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

    public synchronized void stop() {
        try {

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 100000000 / amountOfTicks;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0;
        while (running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1) {
                tick();
                delta--;
            }
            if (running)
                render();
            frames++;

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

    private void tick() {
        handler.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);  

        handler.render(g);

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

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

1 个答案:

答案 0 :(得分:1)

正如 eldo 所建议的那样,

  

据我所见,您从未设置running变量true。您的框架显示但您的游戏循环实际上从未实际到达render方法。在running = true;方法中尝试start

请检查running布尔变量。如果是这种情况,请将其答案标记为已接受。

否则,您也可以尝试以下代码段:  通过paint方法并将Graphics投射到Graphics2D

@Override
  public void paint (Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(Color.blue);
    g2.fillRect(50, 50, 300, 300);  

  }