簡體   English   中英

空指針異常添加工具欄

[英]Null Pointer Exception Adding a Toolbar

我正在嘗試向程序中添加工具欄,但是當我添加代碼時,我得到了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) 

“我正在得到一個nullpointerexception,有人知道為什么會這樣嗎?”

java.lang.NullPointerException at javax.swing.ImageIcon

由於路徑錯誤,URL為空,因此您將得到nullpointerexception ,並將空URL傳遞給ImageIcon

您需要另一個/路徑前面

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

您的images必須直接是src的子級

ProjectRoot
          src
              images
                   someimage.jpg                   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM