Search code examples
javaimageembedded-resource

How to access an image in a different folder?


How would I access a picture in a different folder in Java? I have a series of pictures and they change based on user input, which is what x is for.

picture.setIcon(new ImageIcon("\\resources\\icons\\pictures\\"+x+".png"));

The images are located (from the .class files) in resources/icons/pictures, but the above code doesn't work. The value of x isn't the problem since it works as it should. Am I calling the pictures the right way?


Solution

  • Am I calling the pictures the right way?

    Probably not. If they are (embedded) application resources they will typically be in a Jar and unavailable via the String based constructor of the ImageIcon (which expects the String equates to a File path).

    For an embedded resources, access them by URL.

    URL urlToImg = this.getClass().
        getResource("/resources/icons/pictures/"+x+".png");
    picture.setIcon(new ImageIcon(urlToImg));