Where to store the images so that the jar executable can access them?

I am using Eclipse to generate an executable jar from a game I have created, but when I create a jar and run it, the images in the game are no longer displayed. Where can I store images so the jar file can access them?

+3


source to share


4 answers


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

+8


source


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

      

0


source


import java.net.URL; 

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

      

0


source


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!

0


source







All Articles