Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getClass().getResource("file") leads to NullPointerException

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.

like image 950
kapitanluffy Avatar asked Apr 24 '11 07:04

kapitanluffy


2 Answers

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 /

like image 174
Bozho Avatar answered Sep 21 '22 18:09

Bozho


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.

like image 22
Harry Joy Avatar answered Sep 23 '22 18:09

Harry Joy