我正在阅读一本关于 Java 编程的书,如果我不明白它正在加载一个位图或者这里的代码,我就参与其中
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL("castle.png"));
我想告诉它图像实际在哪里或什么的get URl是什么?
当我像这样运行它时,它如何找到我得到这个错误的图像 -
Uncaught error fetching image:
java.lang.NullPointerException
这是完整的代码 -
package randomshapes;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.net.*;
public class RandomShapes extends JFrame{
private Image image;
public static void main(String [] args){
new RandomShapes();
}
public RandomShapes(){
super("DrawImage");
setSize(600,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL("castle.png"));
}
private URL getURL(String filename){
URL url = null;
try{
url = this.getClass().getResource(filename);
} catch (Exception e){ }
return url;
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, getSize().width, getSize().height);
g2d.drawImage(image, 0, 40, this);
}
}