I am using Eclipse to make an executable jar file of a game I created, but when I create the jar and run it, the images in the game no longer show up. Where do I store the images so the jar file can access them?
Asked
Active
Viewed 6,546 times
4 Answers
8
Put them in the jar, and then use Class.getResource
, Class.getResourceAsStream
, ClassLoader.getResource
or ClassLoader.getResourceAsStream
to access them. Which is most appropriate depends on what else you're doing, but you might want something like:
Image image = new Image(Program.class.getResource("/images/foo.jpg"));
... where Program.class
is any class within the same jar file. Or if you're storing your images in the same folder as your classes (by the time you're deployed) you could just use:
Image image = new Image(GameCharacter.class.getResource("knight.jpg"));
That's a relative resource name. (Relative to the class in question.)

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
If I type it like that, it says "Cannot Instantiate the Type Image". I have a class called Resources and an image called MountainBackground, so I wrote Image image = new Image(Resources.class.getResource("MountainBackground.png")); – ramuh1231 Feb 18 '13 at 16:03
-
@user2081893: That was just a random example - hence the "something like". We don't know what sort of app you're writing, or what image class you're using. You should adapt it accordingly - or provide more information in the question. – Jon Skeet Feb 18 '13 at 16:08
1
import java.net.URL;
URL imageURL = getClass().getResource("/Icon.jpg");
Image img = tk.getImage(imageURL);
this.frame.setIconImage(img);

sarath
- 767
- 12
- 19
1
My file structure is:
./ - the root of your program
|__ *.jar
|__ path-next-to-jar/img.jpg
Code:
String imgFile = "/path-next-to-jar/img.jpg";
InputStream stream = ThisClassName.class.getClass().getResourceAsStream(imgFile);
BufferedImage image = ImageIO.read(stream);
Replace ThisClassName
with your own and you're all set!

ddaaggeett
- 149
- 2
- 10
0
Why can't you embed them within the jar file?
UPDATE: How I did in one of my assignments is as follows: Embedded the images in the jar file, and:
URL url = getClass().getResource("/banana.jpg");
if (url == null)
{
// Invalid image path above
}
else
{
// path is OK
Image image = Toolkit.getDefaultToolkit().getImage(url);
}