I am following the 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 /
Try this:
ImageIcon iid = new ImageIcon(this.getClass()
.getClassLoader().getResource("ball.png"));
ball = iid.getImage();
Make sure image is in the same folder as java file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With