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

52,458

Solution 1

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 /

Solution 2

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.

Solution 3

Try using System.out.println(System.getProperty("java.class.path")); to find out location of your .class file and place the images in this folder.

Solution 4

It is general risky to load resources using relative paths, I'd always recommend using absolute paths, so do

 /ball.png

if the the image is at the root of your classpath, or add a path to the location.

Solution 5

You have to put the image file(ball.png) into your classpath. More details, please take a look at the Javadoc.

Share:
52,458
kapitanluffy
Author by

kapitanluffy

Updated on May 16, 2021

Comments

  • kapitanluffy
    kapitanluffy almost 3 years

    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.

  • kapitanluffy
    kapitanluffy about 13 years
    so by that you mean i should add the ball.png to the resource?how?
  • user207421
    user207421 about 13 years
    @kapitanluffy: You seem to be using the resources API without knowing the first thing about what it's for. I suggest you read the Javadoc.
  • user207421
    user207421 over 10 years
    Thse two sentences re mutually contradictory. Using the class loader method loses the information about where the .class file is.