ramuh1231
ramuh1231

Reputation: 47

Where do I store images so that an executable jar file can access them?

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?

Upvotes: 3

Views: 6700

Answers (4)

ddaaggeett
ddaaggeett

Reputation: 177

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!

Upvotes: 1

sarath
sarath

Reputation: 893

import java.net.URL; 

URL imageURL = getClass().getResource("/Icon.jpg");
Image img = tk.getImage(imageURL);
this.frame.setIconImage(img);

Upvotes: 1

user517491
user517491

Reputation:

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);
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500865

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.)

Upvotes: 8

Related Questions