I’m creating a Java application in NetBeans, and I have the following code that sometimes gets called after a button click to put a provided image and string onto a JLabel that was placed in the GUI Builder:
helpLabel.setIcon(new ImageIcon("/bepe/resources/" + e.imageFile));
helpLabel.setText(e.getMessage());
The images are located in the sub-directory “resources”, which is in the same location as the files for the program. The label’s text is set as expected, but the image does not appear. If I set an image ahead of time in the GUI Builder, the image shows up. The generated code for that is
helpLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bepe/resources/orIntro.png")));
But when I try to set the icon in the same way, I get a run-time error. Is there something wrong with the way I’m setting the image?
This declaration presumes the image is on the run-time class-path of the application, and accesses it by URL. This is the way to access a resource in a Jar.
This declaration presumes the
Stringargument represents aFilepath. It will not work for an ‘application resource’ that is (presumably) in a Jar.Use
getResourceconsistently, and make sure the image is on the run-time class-path.