Search code examples
javaswingnullpointerexceptioniconsembedded-resource

Cannot display icon - Uncaught error when fetching image


I want to display another icon instead of the usual java load icon. I have put that into this folder:

enter image description here

I want to load it over the getResource() method.

setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("house.png")));

However, I am getting:

Uncaught error fetching image:
java.lang.NullPointerException
    at sun.awt.image.URLImageSource.getConnection(Unknown Source)
    at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
    at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
    at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
    at sun.awt.image.ImageFetcher.run(Unknown Source)

Why does getResource() not load my picture from my folder? I appreciate your answer!


Solution

  • Just for an explanation of why @MadProgrammer's comment ("/house.png") worked:

    You are using maven. Files in src/main/resources become resources on the class path. Ultimately placed at the root of the classpath, with no main/resources. So you're intuition was correct, initially just using "house.png" as the path, as the image is at the root.

    What you failed to consider though is where the call is coming from. When you use Class.getResource, the call will begin the search from the location of the class, i.e the package where the calling class is located. So for instance if you have something like

    src
       main
           resources
                   house.png
       main
           java
               com
                  mypackage
                          CallingClass.class
    

    The search will being in com/mypackage. So for this path ("house.png") to work, the image would have to be in the com/mypackage package, but it's not. It's in the root.

    That brings us to the forward slash /. That that forward slash ultimately does, is make the search start from the root of the class path. So with the forward slash ("/house.png"), the search will find the image in src/main/resources, which ultimately in the root of the classpath.