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)...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| 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; 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...
1 2 3 4
| 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
1 2
| offscreenImage = createImage(width, height); offscr = offscreenImage.getGraphics(); |
should of been place in paint().