Search code examples
javaeclipseimagenullpointerexceptionresources

getClass() getResource returning null


When I try and load a image from a resource directory in eclipse I keep getting a null pointer exception (NPE). The res folder is in the project directory. This where I get the NPE:

image.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("res/bg.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));

When I remove the getClass().getReource() the image is returned:

image.setIcon(new ImageIcon(new ImageIcon(("res/bg1.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));

When I print the URL for the res directory I get null:

URL resource = this.getClass().getResource("/");
        resource.getFile(); // print me somehwere

        URL resource1 = this.getClass().getResource("/res");
        resource.getFile(); // print me as well

        URL resource2 = this.getClass().getResource("res/bg2");
        resource.getFile(); // print me as well

        System.out.println("Reource1 : " + resource);
        System.out.println("Reource1 : " + resource1);
        System.out.println("Reource1 : " + resource2);

Output:

Reource1 :file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
Reource1 : null
Reource1 : null

I have refreshed, cleaned, and built the project several times.

Directory: enter image description here

Any idea why this is happening?

Thanks


Solution

  • Replace this.getClass().getResource("res/bg.jpg") with this.getClass().getResource("../res/bg.jpg")

    Since this.getClass().getResource("/") returns file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/, you need to go one level(directory) up in the directory structure so that you can enter the res directory. It's like cd ../res from the current location of file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/

    Note: I can't see bg.jpg in the screenshot that you have attached. Make sure, you have bg.jpg in this path.