[英]Null Pointer Exception Adding a Toolbar
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? 我正在尝试向程序中添加工具栏,但是当我添加代码时,我得到了nullpointerexception,有人知道为什么会发生这种情况吗?
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?"
“我正在得到一个nullpointerexception,有人知道为什么会这样吗?”
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
由于路径错误,URL为空,因此您将得到
nullpointerexception
,并将空URL传递给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
您的
images
必须直接是src
的子级
ProjectRoot
src
images
someimage.jpg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.