How to use getClass () method. GetResource ()

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

iconX = new ImageIcon (getClass().getResource("imageX.png")) 

The above code works correctly either in the applet or in the desktop application when .png is in the same class folder.

Question: how to avoid NullPointerException when .Png is in another folder? Or how to load an image in an ImageIcon when it is located elsewhere in the class?

I don’t understand how this method works, if someone can help me, I appreciate it. Thanks!!

+6
source share
3 answers

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.

+4
source

Just specify the path to the resource.

So, if you put the image in "/ resources / images" in your Jar, you'll just use

 iconX = new ImageIcon(getClass().getResource("/resources/images/imageX.png")) 

Essentially, you say class loader, please look for your path to the next resource.

+1
source

If the image is internal (you want the location relative to your project, or perhaps packed in your jar), do what the crazy programmer said:

 iconX = new ImageIcon(getClass().getResource("/path/imageX.png")) 

The path is relative, so the path / will be a folder in the same folder as your project (or packaged in your jar).

If you want to get an external image, just handle the ImageIcon path (for example, C: /.../ file.png). However, this is not recommended, as it is better to use it as a resource.

Read more about the ImageIcon constructor here . for more information on loading class resources see here (Javadoc links)

+1
source

Source: https://habr.com/ru/post/923621/


All Articles