Take a look at this - Class#getResource(java.lang.String)
Please follow the link above and read the documents and follow to understand what is happening.
It says -
If the name begins with '/', then the absolute name of the resource is part of the name following '/'.
and
Otherwise, the absolute name has the following form:
modified_package_name/name
If the name modified_package_name is the package name of this object , where '/' is replaced by ..
So, if this object (where you call getResource ) is in the package /pkg1 ( / means that pkg1 is under the root of the class path) and you used "imageX. Png", then the result will be pkg1/imageX.png , which is correct because this is where the image is located.
But if we moved the resource (imageX.png) to another package /pkg2 , and you called the method in the same way, then the result would still be pkg1/imageX.png , but this time it would be wrong, because the resource itself located in /pkg2 . This is when you are done with NPE.
Itβs good to specify the full path of the resource, starting with the root of the class path. (e.g. "/pkg/imageX.png").
Hope this helps.
source share