Tyler Petrochko
Tyler Petrochko

Reputation: 2641

Java .Jar Image Not Showing Up

I made an application in Java (using the Eclipse IDE) and i refer in the code to images stored in a source folder called "source" and it worked fine in the IDE. When I extracted the jar to an runnable jar, there are no errors but the picture doesn't show up, or if it does it just shows whatever's behind it. I opened up the .jar in WinRar and it appears the pictures are all thrown in with the class files. How can I fix this?

Image i = Toolkit.getDefaultToolkit().getImage("sources/SystemTrayOne.png");

Upvotes: 1

Views: 940

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

You're trying to get a file which doesn't exist in a Jar. Instead get the URL via the Class#getResource(...)

e.g.,

URL imgUrl = getClass().getResource(....); // resource name here
Image i = Toolkit.getDefaultToolkit().getImage(imgUrl);

or better

URL imgUrl = getClass().getResource(....); // resource name here
Image i = ImageIO.read(imgUrl);

Upvotes: 4

Atul Dureja
Atul Dureja

Reputation: 27

I was also facing the same issue till yesterday. I have got a fix for this. Let me share it with you.

  • In your Eclipse, go to your Project name.
  • Right your project name.
  • New -> Source file/folder
  • Name this Source file/folder as images
  • Now on your local machine go to the Eclipse workspace where your project is physically present.
  • Copy ALL your images into the newly created 'images' folder right there only.
  • Now go back to Eclipse.
  • Right click on your Project -> Refresh
  • Now, wherever you are using images in your .java files , go to those lines and prefix the image location with images/

Example : XXX xxx = XXXX (example.jpg) Change it with .... XXX xxx = XXXX (images/example.jpg)

BOOM !! The images will be shown when you run the .jar file.

NOTE : Do not run the .jar file from cmd using java -jar AppName.jar Instead, just double click the .jar file and you will be seeing the images.

If it works for you, kindly upvote. :)

Upvotes: 2

Related Questions