Original Post
After following Glass Knife's article on active rendering I succeeded in getting everything to work fine in a single class. However, I'm now trying to create a separate Rendering class to completely separate rendering from game logic. The code I have compiles but when run it generate a NullPointerException (line 14 in main, line 44 in Draw). This is what I have so far and I'm pretty sure I'm trying to implement this completely wrong. All help appreciated.
public class TileGame {
public static void main(String[] args) {
Draw draw = new Draw();
GameTimer timer = new GameTimer(60);
while(true) {
try {
timer.start();
draw.preDrawMethod();
draw.box();
draw.postDrawMethod();
timer.syncTime();
}
finally {
draw.destroy();
}
}
}
}
import javax.swing.JFrame;
import java.awt.*;
import java.awt.image.*;
public class Draw {
private final int SCREEN_WIDTH = 640;
private final int SCREEN_HEIGHT = 480;
private JFrame window = null;
private Canvas canvas = null;
private BufferStrategy buffer = null;
private GraphicsEnvironment ge = null;
private GraphicsDevice gd = null;
private GraphicsConfiguration gc = null;
private BufferedImage bi = null;
private Graphics g = null;
private Graphics2D g2d = null;
public Draw() {
window = new JFrame();
canvas = new Canvas();
window.setIgnoreRepaint(true);
canvas.setIgnoreRepaint(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
window.add(canvas);
window.pack();
window.setResizable(false);
window.setVisible(true);
canvas.createBufferStrategy(2);
BufferStrategy buffer = canvas.getBufferStrategy();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage bi = gc.createCompatibleImage(SCREEN_WIDTH, SCREEN_HEIGHT);
}
public void preDrawMethod() {
g2d = bi.createGraphics();
}
public void postDrawMethod() {
g = buffer.getDrawGraphics();
g.drawImage(bi, 0, 0, null);
buffer.show();
}
public void destroy() {
if (g != null)
g.dispose();
if (g2d != null)
g2d.dispose();
}
public void box() {
g2d.setColor(Color.BLUE);
g2d.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}
}