How to use getClass().getResource() method

前端 未结 3 1543
自闭症患者
自闭症患者 2020-12-06 07:30

When I create ImageIcon class objects I use the following code:

iconX = new ImageIcon (getClass().getResource(\"imageX.png\"))
相关标签:
3条回答
  • 2020-12-06 07:34

    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)

    0 讨论(0)
  • 2020-12-06 07:36

    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.

    0 讨论(0)
  • 2020-12-06 07:53

    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.

    0 讨论(0)
提交回复
热议问题