GladL33
GladL33

Reputation: 53

How do store images in my application without having to give the exact directory of the image?

At the moment, I'm trying to get a background image for my app and I have to specify the exact location of the image in the code like so

// Add image to the background
    try {
        setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Users/Dropbox/Team Project/AutoRepair/AutoRepairSystem/src/res/bg_login2.png")))));
    } catch (IOException e) {
        System.out.print("Image did not load!");
    }    

I have the images stored in my res folder, but I still have to change the first 2-3 folder names every time I run the code on another machine.

This is really frustrating considering I have about 20 java files and about 20 images that I have to go through.

Upvotes: 0

Views: 384

Answers (3)

GladL33
GladL33

Reputation: 53

Ok, so what I did was create another source folder in my project and named it "img" and put my images into it. So now I don't have to type out the whole directory like I did before but instead just put /img/bg_login2.png and it works great.

try {

        setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("img/bg_login2.png")))));
    } catch (IOException e) {
        System.out.print("Image did not load!");
    }

Upvotes: 0

arcy
arcy

Reputation: 13123

This is what Class.getResourceAsStream() and related methods are for -- you store the images in the same location as a given class, and then you can use that class to locate the images. This way the images can be in a JAR file, and the code still runs fine. Look up a tutorial on how to use this facility, then you won't have to change code for a different machine.

Upvotes: 1

copeg
copeg

Reputation: 8348

Place the images within the package(s) of your project. This way the images can be moved with the project, or packaged into a jar file. To access resources in this manner, you can use the getResource() or getResourceAsStream() methods of Class:

URL urlToResource = MyClass.class.getResource("/path/to/image");//alternative, you can use the getClass() method of object
ImageIcon icon = new ImageIcon(urlToResource);

Note the path is dependent upon where you place the file. You can use an absolute path (preceeded by a '/') or a relative path (relative to the location of the calling class).

Upvotes: 1

Related Questions