NullPointerException when using path name to load image file

Looked everywhere and still can not find a solution to this problem when using NetBeans.

When I use the following code to upload a file along the path:

Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage(); 

I get a NullPointerException. I read somewhere where I suggested creating a new folder and making it the source file for the project, but that did not help. I tried several offers that I found on this site and others, but I am not getting any results.

I am starting to wonder if there is something wrong with the way I put in this path, but I do it exactly as it shows everywhere. I tried every combination of each example that I could find to solve this problem in the last few days, but nothing works.

+4
source share
2 answers

It seems that the images folder was not part of your class path. In Eclipse, this is not what they call the build path.

Right-click on the images folder, select "Build Path" and use as the source folder. Now the folder will be added to the classpath whenever you launch the application through Eclipse. If you do, you need to change your path to

 Image owl = new ImageIcon(this.getClass().getResource("/owl.gif")).getImage(); 

because now everything in images will be placed directly in the classpath.

Instead, you can make a package called images in your regular src folder and name it

 Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage(); 
+3
source

.getResource() returns null when it cannot find the resource. That you get a null value.

Your problem is that the path for owl.gif wrong.

+1
source

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


All Articles