java 获取图像的问题
来源:百度知道 编辑:UC知道 时间:2024/06/17 00:47:06
图片放在项目目录的images里面,images跟src同级。
代码如下:
public class ImageURL {
public static URL getImageURL(String name) {
return ImageURL.class.getResource("/" + name);
}
}
当我用其它类的方法调用上面那个类取得URL时,却返回null
public class Test {
public void test() {
URL url = ImageURL.getImageURL("photo.gif");
ImageIcon image = new ImageIcon(url);
}
}
就像上面这个Test类里的test方法调用时,返回的URL是空的,请问我哪里有错,找半天了,找不出原因。
我找到原因了,原来我建的那个images目录是Folder,只要建成Source Folder就可以了
代码如下:
public class ImageURL {
public static URL getImageURL(String name) {
return ImageURL.class.getResource("/" + name);
}
}
当我用其它类的方法调用上面那个类取得URL时,却返回null
public class Test {
public void test() {
URL url = ImageURL.getImageURL("photo.gif");
ImageIcon image = new ImageIcon(url);
}
}
就像上面这个Test类里的test方法调用时,返回的URL是空的,请问我哪里有错,找半天了,找不出原因。
我找到原因了,原来我建的那个images目录是Folder,只要建成Source Folder就可以了
楼主应该是在Eclipse下开发的吧,假设你的工程名为MyProject吧,此时下面有src,src下你可以建包放类文件,用System.out.println(System.getProperty("user.dir")); 可以输出当前路径,此时会得到路径为MyProject下,所以
如果你在MyProject下新建images,和src同级的话,那么你的return ImageURL.class.getResource("/" + name);应该改为
return ImageURL.class.getResource("/images/" + name);
试试吧
去掉你的/试试?return ImageURL.class.getResource(name);