An 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 compiled 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?
The reason that you get a NullPointerException is because for some reason the image file that you're trying to specify cannot be located. So the getResource()
method returns a null.
As a start, you can read about adding icons in this link: "How to Use Icons"
One of the ways that they suggest is by creating 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 having this method, apart from being a utility method that you can use multiple times whenever you want to add an icon, is that it also shows you the error in case the image could not be located at the path specified.
I strongly suspect that this has to do with the path that you've provided. It would be good to look at the folder structure. Try passing the path as "project/print.gif"