I'm struggling and need a little help please. My application which I'm running from the Eclipe IDE loads images for icons for buttons using code like this which works fine.
result = new ImageIcon(Common.image_path+filename);
However I ultimately want to package my application into a JAR file and I've tried to replace this code with many variants of this :-
ClassLoader cldr = this.getClass().getClassLoader(); java.net.URL imageURL = cldr.getResource("\\Java\\eclipse\\workspace\\b4images"+filename); result = new ImageIcon(imageURL);
I'm not sure if this would work if the application would run as a .JAR file, but imageURL is always null when I run it as a regular java program.
Is there a way to code it so that it works in either mode. Also I'm unsure about how the path should look. The images are held in a subdirectory called "Images" which is a subdirectory off my main project workspace. However the classloaded is part of a class in a java package, does the path have to be relative to the workspace or the class or neither ?
I hope I'm not beating a dead horse, but it's necessary to use URLs, not Files, to identify resources like images so that your program works whether it is zipped in a jar or not. Avoid constructor ImageIcon(String filename), since it assumes the parameter is a file system path. If the image is in the same folder as file X.class (whether that folder is in the file system or a "folder" in a jar file), the following will work:
URL url = X.class.getResource("sample.jpeg"); Icon icon = new ImageIcon(url);
But it's better to separate resources from code, so suppose we have the organization:
So when the code is in a jar, "/images/sample.jpeg" denotes a "path" in the jar file and when the code isn't zipped, "/images/sample.jpeg" extends the folder that contains the start of the package hierarchy. That sounds more complicated than it really is. Once you've set things up (and I prefer using Ant), it's a snap.
So relative to the starting point I have currently referenced my gif files by using a path "./Images/mypic.gif"
Using your syntax then I should be using a url instead of a path and change it to "/Images/mypic.gif"
What is it that determines the root for the URL then ? If my batch file that started the app was it a different directory with a different default directory would with make a difference ?