我的第一个问题:
我一直试图解决这个问题几天,但我已经到了失去耐心的地步.以下是一些代码和我的项目结构.
问题:如何getResources()在eclipse中和导入jar后工作?
谢谢您的帮助.
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);
}
}
Run Code Online (Sandbox Code Playgroud)

通常情况下,从出口Eclipse的一个JAR文件时,内容src/resources出口减去的src路径名称本身.要从JAR加载图像,您可以执行以下操作:
InputStream stream = getClass().getResourceAsStream("/resources/icons/xyz.png");
ImageIcon icon= new ImageIcon(ImageIO.read(stream));
Run Code Online (Sandbox Code Playgroud)
确切知道的一种方法是检查:
jar tvf yourjar.jar
Run Code Online (Sandbox Code Playgroud)
如果 png 文件已打包到 JAR 中,位置与原始 src 目录中的位置相同,则
XXX("resources/icons/xyz.png");
Run Code Online (Sandbox Code Playgroud)
应该产生正确的结果。