Null pointer exception when an ImageIcon is added to jbutton in NetBeans
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"