Search code examples
javaswingembedded-resource

Why does the JVM claim my PNG does not exist?


I am trying to set the upper-left image on a JFrame. However, it claims my PNG file is nonexistant. I set the icon with

mainFrame.setIconImage(new ImageIcon(getClass().getResource("C:/Users/Steve/Programming/Projects/Java/BibleReader/bibleReader/src/test/resources/assets/bible/textures/icon.png")).getImage());

This is the error

Exception in thread "main" java.lang.NullPointerException at
javax.swing.ImageIcon.<init>(Unknown Source) at
com.nickson.input.UI.prepareGUI(UI.java:42) at
com.nickson.input.UI.<init>(UI.java:33) at
com.nickson.main.Engine.main(Engine.java:19)

Why is this happening?


Solution

  • Why is this happening?

    You are trying to open a resource with a path in the file system. Resource paths should be relative to a directory or JAR file on the application classpath.

    So in your particular case, the classloader is looking for a resource folder called "C:" relative to the resource location of current class. Naturally, it doesn't exist. And since getResource returns null if it cannot find a resource, this leads to an NPE.

    Here are a couple of pages with detailed explanation of how resource loading and resource path resolution actually works:


    As a guess, and assuming that you are using Maven, I think that the path "/assets/bible/textures/icon.png" would work if your code is running in a unit test. For production code, I think you have the resource in the wrong tree; it should be in the .../main/resources/ tree.