Search code examples
javajframeimageicon

Image won't load from root of jar


I want to be able to load an image from inside the jar.

Many pages say to use the exact code I am using. Some say to use getClass(), but I am running the code in my main method and my class is not static.

Currently I have the following code in the main method on the main class.

try {
    ImageIcon icon = new ImageIcon(BlockWorld.class.getResource("icon.png")); // line 46
    window.setIconImage(icon.getImage());
} catch (Exception e) {
    e.printStackTrace();
}

I know for a fact that icon.png is in the root of the jar. It is a 128 x 128 png with no alpha.

Everything compiles fine. When I run the jar, it put out the following.

java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at com.Tgwizman.BlockWorld.BlockWorld.main(BlockWorld.java:46)

Does anyone have any suggestions?


Solution

  • Add a leading slash to the path to use the root folder of the jar.

    getResource("/icon.png")