Reputation: 796
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?
Upvotes: 1
Views: 2985
Reputation: 36269
The images are located (from the .class files) in resources/icons/pictures
That's a problem. The system isn't interested in where the class file is, but from where you invoke a program.
Specifying a resource folder via command line,
java -jar myJar.jar C:\\home\\of\\the\\images
or via a property
java -jar myJar.jar -DImageHome=/foo/bar/images
or from a properties file is most flexible.
If you like to put the images into the jar, use Andrews suggestion, getClass ().getRessource ("...");
Btw: I know for sure, that forward slashes are portable. Backslashes, afaik, aren't.
Upvotes: 0
Reputation: 168845
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));
Upvotes: 2
Reputation: 106401
You should be using forward slashes instead of backslashes I believe.
new ImageIcon("/resources/icons/pictures/"+x+".png")
This is the standard Java cross-platform way of denoting resource file paths. It still works on Windows - the Java runtime library handles the transaltion for you.
Upvotes: 0