I have a very simple Game Engine that I am trying to set up and I am clueless as to why it is throwing an exception but I'm not very experienced so I understand I'm probably doing something wrong.
I want to draw directly to a JFrame with a buffer strategy using the Graphics class. Everything works until I try to pass the Graphics g in to another class and then I get a thread error. Here is what I have:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class GameFrame extends JFrame implements Runnable {
public static final int WIDTH = 1280;
public static final int HEIGHT = WIDTH * 9 / 16;
private final int FPS = 60;
private Thread thread;
private long lastTime;
private Game game;
public GameFrame() {
game = new Game(this);
setLocation((int) ((Toolkit.getDefaultToolkit().getScreenSize().getWidth() - WIDTH) / 2), (int) ((Toolkit.getDefaultToolkit().getScreenSize().getHeight() - HEIGHT) / 2));
setSize(new Dimension(WIDTH, HEIGHT));
setResizable(false);
thread = new Thread(this);
setVisible(true);
createBufferStrategy(3);
setDefaultCloseOperation(EXIT_ON_CLOSE);
thread.start();
}
public void run() {
lastTime = System.currentTimeMillis();
while (true) {
long time = System.currentTimeMillis();
if ((time - lastTime) * FPS > 1000) {
lastTime = time;
tick();
draw();
getBufferStrategy().show();
}
}
}
private void tick() {
game.tick();
}
private void draw() {
game.draw();
}
public static void main(String[] args) {
new GameFrame();
}
}
and
import java.awt.Graphics2D;
public class Game {
private GameFrame frame;
private Map map;
public Game(GameFrame frame) {
this.frame = frame;
}
public void tick() {
}
public void draw() {
Graphics2D g = (Graphics2D) frame.getBufferStrategy().getDrawGraphics();
g.fillRect(0, 0, 50, 50);
map.draw(g);
g.dispose();
}
}
The rectangle from the draw method inside of Game will work but if I pass g to my Map class (which will be drawing the same thing) it causes a thread NullPointerException.
Thanks so much in advance for any help with this or any additional comments you can provide!