Null pointer exception when ImageIcon is added to jbutton in NetBeans

ImageIcon is added to button properties using NetBeans.

print.setFont(new java.awt.Font("Serif", 0, 14)); print.setIcon(new javax.swing.ImageIcon(getClass().getResource("/project/print.gif"))); print.setMnemonic('P'); print.setText("Print"); print.setToolTipText("Print"); 

And when compiling it shows

 Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(ImageIcon.java:205) at project.Editor.initComponents(Editor.java:296) 

What am I doing wrong?

+6
source share
2 answers

The reason you get the NullPointerException is because for some reason the image file you are trying to specify cannot be found. Therefore, the getResource() method returns zero.

In the beginning, you can read about adding icons to this link: "How to use icons"

One way they suggest is to create a method:

 /** Returns an ImageIcon, or null if the path was invalid. */ protected ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } else { System.err.println("Couldn't find file: " + path); return null; } } 

The advantage of using this method, in addition to using the utility method, which you can use several times when you want to add an icon, is that it also shows you an error if the image cannot be installed on the specified path.

I strongly suspect that this is due to what you provided. It would be nice to look at the folder structure. Try passing the path as "project / print.gif"

+6
source

The expression getClass().getResource("/project/print.gif") calls the getClass method (inherited indirectly from the Object class) to get a reference to the class object that represents the "Class Class" declaration (your class). This link is then used to invoke the getResource class method, which returns the location of the image as a URL. The ImageIcon constructor uses the URL to search for the image, and then loads it into memory. The JVM loads class declarations into memory using the class loader. The class loader knows where each loaded class is located on disk. The getResource method uses a class object class loader to determine the location of a resource, such as an image file. Therefore, you get a NullPointerException and the image file should be stored in the same place as the Editor.class file. The methods you tried to use here allow the application to load image files from locations related to the location of class files.

Because of this, you must move the file "print.gif" to the folder "/ projectName / bin / packageName" and try

print.setIcon(new javax.swing.ImageIcon(getClass().getResource("print.gif")));

instead

print.setIcon(new javax.swing.ImageIcon(getClass().getResource("/project/print.gif")));

0
source

All Articles