How to change source file of images just to the folder?

Hi I'm still new to programming, Im creating a gui app that includes a lot of images. I want to send my work to a colleague but the program wont work because the images will have a different file directory:

labelPic.setIcon(new ImageIcon("C:\\Users\\Jordan\\eclipseworkspace\\GuiProject\\src\\images\\loadingPic.gif"));

How would I be able to change the directory so that other people can open and edit the program when I send it to them?


Solution 1:

Eventually you'll pack your app into a jar file. Just like your class files are a fundamental part of the app and without them the installation is broken, the same applies to your icons.

Thus, the obvious answer: Store the images the same place you store your class file, and use the same mechanism to load em. Even if they are a jar (meaning, they aren't a file at all, and you simply can't use that constructor - at all, that is only for files and the aim is to not even have a file here, the aim is to have an entry in a jar).

Fortunately, it's easy, but a thing or two depends on how you build / develop the app. Your code should look like this no matter what build you use:

labelPic.setIcon(TheClassThisCodeIsIn.class.getResource("/images/loadingPic.gif"))

The only question is: What do you need to do to your build process to make it work. From the style of that path I'm pretty sure the answer is: Nothing, this will just work fine, both when running it straight inside eclipse as well as when you tell eclipse to package it up into a single jar.

What that line does

Foo.class is valid java, but a bit exotic. It means: Get me a java.lang.Class<?> reference for the named class. You want your own class's reference, as we'll be asking is to load a resource from where-ever it was loaded. We're going to be putting these images in the same place the class file for this code is, so that's why we ask your own class instance for this data.

getResource returns a URL. ImageIcon knows what to do with it, you don't have to know.

/images/loadingPic.gif then specifies the resource name. This is not a file name. Hence, forward slashes (doesn't matter if you end up running this on windows, as I said, not a file path, a java resource name). Because we started the name with a leading slash, the loader will look at the 'root' of whereever YourClass.class is. For example, if YourClass.class is in a jar file, it'll look in the 'root' of the jar for a folder named 'images', and from there, an entry named 'loadingPic.gif'.