When I create ImageIcon class objects I use the following code:
iconX = new ImageIcon (getClass().getResource("imageX.png"))
The above code works correctly either in an applet or a desktop app when the .png is in the same folder of the class.
The question is: how to avoid a NullPointerException
when the .Png is in another folder? Or how load the image in the object ImageIcon
when it is in a different location to the class?
I don't understand how this method works, if anyone can help me I appreciate it. Thanks!!
Take a look at this - Class#getResource(java.lang.String)
Please click the link above and read the docs and follow to understand what's going on.
It says -
If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.
and
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.'.
So, if this object (where you call getResource
) is in package /pkg1
(/
meaning pkg1 is right under the root of the classpath) and you used "imageX.png" then the result would be pkg1/imageX.png
which is correct because that's where the image is located at.
But, if we moved the resource (imageX.png) to some other package /pkg2
and you called the method same way then the result would still be pkg1/imageX.png
but this time it would be incorrect because the resource is actually located in /pkg2
. That's when you end up with NPE.
It's good to explicitly specify the full path of the resource starting from the root of the classpath. (e.g. "/pkg/imageX.png").
Hope this helps.
Simply supply the path to the resource.
So, if you put the image in "/resources/images" within your Jar, you would simply use
iconX = new ImageIcon(getClass().getResource("/resources/images/imageX.png"))
Essentially what you're saying is, class loader, please search your class path for the following resource.
If the image is internal (you want a location relative to your project, or perhaps packaged into your jar), do what mad programmer said:
iconX = new ImageIcon(getClass().getResource("/path/imageX.png"))
The path is relative, so path/ will be a folder in the same folder as your project (or packaged into your jar).
If you want an external image, simply hand ImageIcon constructor the path (ex. "C:/.../file.png"). This isn't recommended though, as it's better to use it as a resource.
For more info on the ImageIcon constructor, see here. for more info on loading class resources, see here (Javadoc links)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With