I have a Java Project in NetBeans 7.0.
I want to add some image to some label dynamically. The image will differ depending on the state of the program.
I put one such image, 'filling.jpg', in the 'resources' folder of my project.
I want to reach this file correctly (not by absolute or relative path, because that will cause problems when I build the jar file).
So I found this method:
ImageIcon fillingIcon = new ImageIcon(getClass().getClassLoader().getResource("filling.jpg"));
labelFontFilling.setIcon(fillingIcon);
It keeps give me java.lang.NullPointerException. But I am sure that there is that image, because I can assign the image to the label from the NetBeans Properties menu for that label (but I don't want this, I want to add the image by Java code).
What am I doing wrong, and how can I get that image correctly?
For me it worked like I had images in
icons
folder undersrc
and I wrote below code.new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
This was a pain, using netBeans IDE 7.2.
Add a resource folder to the src folder:
After the clean/build this structure is propogated into the Build folder:
To access the resources:
and:
worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.
Double click on the executable jar file in the dist folder. The path to the resources still works.
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use
But correct way was use name of my project in path to resource
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
If you were to create a package called Images under the resources folder, you can retrieve the resource like this: