用于 ImageIcon 的 getResources() - java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14104816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getResources() for ImageIcon - java
提问by Fer
my very first question:
我的第一个问题:
I've been trying to figure this out for a couple of days, but I got to the point I lost my patience. The following are some code and my project structure.
几天来我一直试图弄清楚这一点,但我已经失去了耐心。以下是一些代码和我的项目结构。
QUESTION:how can I get getResources()
to work in eclipse and after being imported to jar?
问题:我怎样才能getResources()
在 eclipse 和导入到 jar 之后开始工作?
Thanks for the help.
谢谢您的帮助。
public enum Icons {
XXX("src/resoruces/icons/xyz.png");
private ImageIcon icon;
Icons(String path) {
try {
// will fail miserably in eclipse and after exporting to jar
URL imageURL = getClass().getClassLoader().getResource(path);
icon = new ImageIcon(imageURL);
} catch (Exception e) {
// works like a char in eclipse and after creating the jar file
// with the files in the same directory
System.out.println("getResoruce() did not work");
icon = new ImageIcon(path);
}
}
采纳答案by Ian Roberts
If the png files have been packaged into the JAR in the same locations as they are in the original src directory then
如果 png 文件已打包到 JAR 中的位置与它们在原始 src 目录中的位置相同,则
XXX("resources/icons/xyz.png");
should produce the right result.
应该产生正确的结果。
回答by Reimeus
Normally when exporting a JAR file from Eclipse, the contents of src/resources
are exported minusthe src
path name itself. To get the image to load from your JAR you could do:
通常情况下,从Eclipse中导出一个JAR文件时,内容src/resources
出口减去的src
路径名称本身。要从 JAR 加载图像,您可以执行以下操作:
InputStream stream = getClass().getResourceAsStream("/resources/icons/xyz.png");
ImageIcon icon= new ImageIcon(ImageIO.read(stream));
One way to know for sure is to check:
确定知道的一种方法是检查:
jar tvf yourjar.jar
回答by Jigar Joshi
src
directory is not available in classpath
src
目录在类路径中不可用
InputStream imageInputStream = getClass().getClassLoader().getResourceAsStream("resources/icons/xyz.png");
byte[] imageData = org.apache.commons.io.IOUtils.toByteArray(in)
ImageIcon imageIcon = new ImageIcon(imageData, "description about image");