Reputation: 47
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
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
Reputation: 893
import java.net.URL;
URL imageURL = getClass().getResource("/Icon.jpg");
Image img = tk.getImage(imageURL);
this.frame.setIconImage(img);
Upvotes: 1
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
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