I am trying to add a toolbar to my program but when I add the code, I am getting a nullpointerexception, anyone know why this may be happening?
public JButton makeButton(String imageName,
String toolTipText) {
//Look for the image.
String imgLocation = "images/" + imageName + ".jpg";
URL imageURL = assignment3.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setIcon(new ImageIcon(imageURL));
return button;
}
The exception is
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at assignment3.assignment3.makeButton(assignment3.java:331)
"I am getting a nullpointerexception, anyone know why this may be happening?"
java.lang.NullPointerException at javax.swing.ImageIcon
You're getting a nullpointerexception
because the URL is null, due to a bad path, and you're passing a null URL to the ImageIcon
You need another /
in front of the path
String imgLocation = "/images/" + imageName + ".jpg";
^
And you images
needs to be directly a child of the src
ProjectRoot
src
images
someimage.jpg
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.