0

プログラムにツールバーを追加しようとしていますが、コードを追加すると 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) 
4

1 に答える 1

3

「nullpointerexception が発生しています。なぜこれが起こっているのか知っている人はいますか?」

java.lang.NullPointerException at javax.swing.ImageIcon

nullpointerexception間違ったパスのために URL が null であり、null URL をImageIcon

/パスの前に別のものが必要です

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

そして、あなたimagesは直接の子供である必要がありますsrc

ProjectRoot
          src
              images
                   someimage.jpg                   
                 
于 2014-02-20T07:20:11.657 に答える