简体   繁体   English

ImageIcon 的 getResources() - java

[英]getResources() for ImageIcon - java

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);
       }
   }

项目结构

Normally when exporting a JAR file from Eclipse, the contents of src\/resources<\/code> are exported minus<\/em> the src<\/code> path name itself.通常,从 Eclipse 导出 JAR 文件时,导出src\/resources<\/code>的内容减去<\/em>src<\/code>路径名本身。 To get the image to load from your JAR you could do:要从您的 JAR 中加载图像,您可以执行以下操作:

InputStream stream = getClass().getResourceAsStream("/resources/icons/xyz.png");
ImageIcon icon= new ImageIcon(ImageIO.read(stream));

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");

src<\/code> directory is not available in classpath src<\/code>目录在类路径中不可用

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM