Java 无法获取图像(新手)
我在获取要显示在J帧中的图像时遇到问题。 我确信我把文件放在了正确的位置,并且正确地键入了名称。 这是密码Java 无法获取图像(新手),java,image,jframe,Java,Image,Jframe,我在获取要显示在J帧中的图像时遇到问题。 我确信我把文件放在了正确的位置,并且正确地键入了名称。 这是密码 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;
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,这是写给Cousel的
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);
从错误中可以看出,Castle.jpg不在classloaders类路径上下文中。如果应用程序中没有Jar'ed图像,您可以使用
文件
对象来生成URL
,但我认为这不是您想要做的
你可以:
- 确保正在从程序文件“C:\hw\myProg\Graphics2d”执行
- Jar应用程序(及其资源)