I want to include an image in a programs Jar file (using NetBeans) so that the program can run on any computer. The image I want to include is in a seperate folder from the source code: src\images\Image0.jpg.
If, in the program code, I specify the complete path of the image, then the Jar only executes as long as the image does not move (so if I specify the complete path as C:\User1\Desktop\Image0.jpg, and then delete the image from the desktop, the Jar doesn't run).
If I specify the image path as relative, such as src/images/Image0.bmp, then the program runs in NetBeans, but the Jar doesn't run at all.
Could someone please outline how this is done in NetBeans?
I don't use Netbeans so I'm not sure what part is specific to that IDE. Also, you say that when including the images in the JAR, "the Jar doesn't run at all" but that is not useful information. What goes wrong?
If I understand correctly you have a Jar that contains both the code and resources.
Resources (ignore the fact that it is in a JAR, for the moment) that are on the classpath can be accessed by the ClassLoader.
When the resources are on the classpath you can often get a java.io.File reference to the resource. If you have never done so, I recommend writing some code to play with this idea.
Now obviously you cannot get a File reference to a resource inside a JAR, but if you explore the ClassLoader API you'll see a way to get a reference to the resources as a java.net.URL.
All very interesting, but I suspect in your case you'll want to use getResourceAsStream(...), but it is worth playing with the concepts above since they'll help avoid problems you'lll have if you try to use getResourceAsStream from the start.
No I don't. Resources must be either in the class path or inside JAR files on the class path. Your src folder is not used in either way. Copy the images folder to your bin folder and it should work.
Joined: Apr 09, 2009
Rob Prime wrote:Resources must be either in the class path or inside JAR files on the class path. Your src folder is not used in either way. Copy the images folder to your bin folder and it should work.
In this case it would be the classes folder. This holds all your classes in the package structure. I'm used to using "bin" for that, being an Eclipse user.
Make sure that the images are inside the classes/images folder, then use "/images/img.gif" as your resource path. images will be in the root of the JAR file so it will also be the root of your resource path.
In NetBeans, any resources you place in the src tree will be automatically copied over to the classes tree when you do a Build (or Clean and Build), except those files matching the "Exclude From JAR File" skeletons specified in Project -> Properties -> Build -> Packaging.
Note that the entire build tree, which contains the classes folder, will be emptied out whenever the project is next Clean-ed. If the resource is no longer available in the src tree, it will vanish from the classes tree too.