Reputation: 13
I'm following a tutorial for a simple game engine and for some reason setColor does not work when I try to fill a rectangle. I just get a blank white screen. I've looked at the other similar posts but none of them seemed to help me out. Here is the code:
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();
}
}
Upvotes: 0
Views: 1588
Reputation: 2838
As suggested by eldo,
As far as I can see, you never set your
running
variabletrue
. Your frame shows up but your game-loop never actually reach yourrender
method. Tryrunning = true;
in yourstart
method.
please check the running
boolean variable. If this is the case, please mark his answer as accepted.
Otherwise, you can try following code snippet too:
By paint
method and cast Graphics
to Graphics2D
@Override
public void paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.blue);
g2.fillRect(50, 50, 300, 300);
}
Upvotes: 1