Hi, I have just started games programming (well programming in general - read a few books at home etc) , i have read through most of the tutorials here and have ordered a book from amazon to get me started. Well i have a problem…
This is my code so far (yeah its probably s**t)…
package roadrunner;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.event.*;
public class MainFrame extends Canvas{
private int carx;
private int cary;
private int cardx;
private int cardy;
private int carwidth;
private int carheight;
private Image offscreenImage;
private Graphics offscr;
private int width = 800, height = 600;
/** Creates a new instance of MainFrame */
public MainFrame() {
JFrame frame = new JFrame("Road Runner");
JPanel panel1 = (JPanel)frame.getContentPane();
setBounds(0,0,width,height);
panel1.setPreferredSize(new Dimension(width,height));
panel1.setLayout(null);
panel1.add(this);
carwidth = 30;
carheight = 30;
carx = 100;
cary = 100;
cardx = 0;
cardy = 0;
offscreenImage = createImage(width, height);
offscr = offscreenImage.getGraphics();
frame.setBounds(0,0,width,height);
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void paint(Graphics g){
offscr.setColor(Color.black);
offscr.fillRect(0,0, width, height);
offscr.setColor(Color.blue);
offscr.fillRect(carx, cary, carwidth, carheight);
g.drawImage(offscreenImage, 0, 0, this);
}
public void updateWorld(){
carx = (int)(Math.random()*width);
cary = (int)(Math.random()*height);
}
public void game(){
while(isVisible()){
updateWorld();
paint(getGraphics());
}
}
public static void main(String[] args) {
MainFrame frame1 = new MainFrame();
frame1.game();
}
}
and whenever i run it i get this error…
Exception in thread "main" java.lang.NullPointerException
at roadrunner.MainFrame.<init>(MainFrame.java:58)
at roadrunner.MainFrame.main(MainFrame.java:89)
Java Result: 1
…and i cant seem to figure out why? Oh and this is just to test out problems etc
[EDIT] - I have fixed the problem… it turns out that
offscreenImage = createImage(width, height);
offscr = offscreenImage.getGraphics();
should of been place in paint().