我无法获取要显示在我的 J Frame 中的图像。我确定我将文件放在正确的位置并正确输入了名称。这是代码
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.net.URL;
import javax.swing.JFrame;
public class DrawImage extends JFrame {
private Image image;
public static void main(String[] args){
new DrawImage();
}
public DrawImage(){
super("DrawImage");
setSize(600,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File appBase = new File("."); //current directory
String path = appBase.getAbsolutePath();
System.out.println(path);
Toolkit tk = Toolkit.getDefaultToolkit();
image= tk.getImage(getURL("Castle.jpg"));
}
private URL getURL(String filename){
URL url=null;
try{
url=this.getClass().getResource(filename);
//url=DrawImage.class.getResource(filename);
//url=C:\hw/myProg/Graphics2d/Castle.jpg;
}
catch(Exception e){
System.out.print("spleen:");
}
return url;
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getSize().width, getSize().height);
g2d.drawImage(image, 0, 40, this);
}
}
我得到的是带有黑色但没有图像的JFrame,这写给了cousle。
C:\hw\myProg\Graphics2d\.
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
自然我的图像文件在 C:\hw\myProg\Graphics2d\Castle.jpg 那么我做错了什么?编辑:好的,我发现您可以从这段方便的代码中测试您的 ide 符合哪个文件夹。在 Eclipse 中,它位于 bin 文件夹中。
URL test = DrawImage.class.getResource("/");
System.out.println(test);