空指针异常添加工具栏

时间:2014-02-20 00:28:29

标签: java swing nullpointerexception jbutton jtoolbar

我正在尝试为我的程序添加一个工具栏,但是当我添加代码时,我得到一个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;
}

例外是

Exception in thread "main" java.lang.NullPointerException 
at javax.swing.ImageIcon.<init>(Unknown Source) 
at assignment3.assignment3.makeButton(assignment3.java:331) 

1 个答案:

答案 0 :(得分:3)

  

“我得到了一个nullpointerexception,任何人都知道为什么会发生这种情况?”

     

java.lang.NullPointerException at javax.swing.ImageIcon

您收到nullpointerexception,因为路径错误,因为网址为空,并且您将空网址传递给ImageIcon

路径前需要另一个/

String imgLocation = "/images/" + imageName + ".jpg";
                      ^

images需要直接成为src

的孩子
ProjectRoot
          src
              images
                   someimage.jpg