I am following the zetcode Snake java games tutorial and always get this error:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
ball = iid.getImage();
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at snake2.Board.<init>(Board.java:52)
at snake2.Snake.<init>(Snake.java:10)
at snake2.Snake.main(Snake.java:22)
I actually just copied and pasted the code to see how it works. They are in the right packages too; but when I try to run it, I always end up with this error.
The image should be in the same package (folder in OS terms) as the compiled class. Check whether you have both .class
and .png
in the same folder. If not, you can use classpath-relative paths in getResource(..)
, by starting with /