0

I have a netbeans java GUI project. It contains java files and folder for images. A most important piece of my project is to display image by clicking a button, let's say it NEXT button. When I clicked NEXT button, image will be displayed one by one from IMG folder. I put the image in a label, like this:

lblImage.setIcon(new ImageIcon(getClass().getResource("../IMG/"+ namaGambar[gambarPos])));

I run the program and so far, it works as I want.

Then, I need to create the project into a jar file. I followed Export JAR with Netbeans and this to create jar file of my project and finally I got myProject.jar file in ./dist/ directory.

When I run myProject.jar, I found that there's something wrong. When I clicked NEXT button, the image doesn't display like I've tried in netbeans. I confuse, did I do something wrong in lblImage.setIcon(new ImageIcon(getClass().getResource("../IMG/"+ namaGambar[gambarPos]))); or what's the problem here?

How can I fix this?

Community
  • 1
  • 1

1 Answers1

1

You get resources in a jar using "/" + zip entry name of the data.

Assuming your jar file looks like this:

xyz.jar
   |------IMG
   |       |-------picture1.png
   |       |-------picture2.gif
   |       |-------picture3.jpeg
   .       .
   .       .
   .
   |------org
   .       |-------example
   .       .          |---------MyClass.class
   .       .          .
   .       .
   .

You have to use

"/IMG/"+ namaGambar[gambarPos]

as parameter for Class.getResource.


NetBeans runs programs from folder build/classes and not from the jar file. That explains the different behaviour.

fabian
  • 67,623
  • 12
  • 74
  • 102