how to package images into a Runnable JAR

2019-05-29 03:53发布

问题:

Before... (question deleted)

I'm trying to make a runnable jar from a Swing project.

I add some images in /img folder. Previous version didn't have it and runnable jar was good through export in Eclipse.

Now I guess something is going wrong. In runnable jar I added at same level of main package and META-INF folder, this img folder but it seems GUI does not appear.

Some process before building GUI went good so main class seems ok.

Any suggestion!?

Thanks.

Comments :

Run it on the command line and post the error you get. – Kevin

Any suggestion!?. Yes. post the structure of the jar file, the code which fails, and the stack trace of the exception you get. Otherwise, I don't see how we could help you. – JB Nizet

Did you plop some images into a path the classloader can see? – Perception

After....

So I found the problem, still not the solution:

As I said, I manually put /img inside jar as you can see by first screenshot:

http://img94.imageshack.us/img94/1691/screenshot021ep.jpg

But nothing happens, now I put /img outside jar and GUI starts:

http://img21.imageshack.us/img21/1551/screenshot022jj.jpg

So, how can I package /img folder or icons for my app?

Thanks.

PS: cmd line didn't print anything, the app starts and does some things right except for GUI building.

回答1:

In Eclipse, create a new source folder called "resources". Then, put your image file in the same package as your class, but in your "resources" folder. By doing this, you can use the following code to get your image as input stream:

ClassName.class.getResourceAsStream(imageFileName);


回答2:

i used to had same problems with accessing images

Check out the below link. It provides answers on

  1. Where should i put my images?
  2. How can access them?

Hope it helps

link : http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html

Specifically check the section "Loading Images Using getResource"