0

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?

Tgwizman
  • 1,469
  • 2
  • 19
  • 34

1 Answers1

0

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

getResource("/icon.png")

Tgwizman
  • 1,469
  • 2
  • 19
  • 34
  • Also, shouldn't the `getResource` call be on the ClassLoader? As in `BlockWorld.class.getClassLoader().getResource("/icon.png")` – coladict Jul 10 '16 at 16:47
  • Not in this case. The code now works. I'm not sure why java doesn't have the jar root as the default directory. It took me forever trying to figure this out. When I finally get around to posting a question here, I found http://stackoverflow.com/questions/2593154/get-a-resource-using-getresource that included this question's answer as part of the answer for the other question. – Tgwizman Jul 10 '16 at 16:50
  • 1
    When dealing with this kind of operation it's always important to be sure to provide the correct path for the resource. Also as stated above there is no need to invoke the class loader. – akortex Jul 10 '16 at 17:14