Where to store the images so that the jar executable can access them?
Put them in a jar and then use Class.getResource
, Class.getResourceAsStream
, ClassLoader.getResource
or ClassLoader.getResourceAsStream
to access them. Most importantly depends on what else you are doing, but you might need 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 save your images in the same folder as your classes (at the time of deployment), you can simply use:
Image image = new Image(GameCharacter.class.getResource("knight.jpg"));
This is the relative name of the resource. (Relative to the class in question.)
source to share
Why can't you embed them in the jar file?
UPDATE: . How I did it in one of my assignments: Attached images to 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);
}
My file structure:
./ - 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!
source to share