繁体   English   中英

ImageIcon 的 getResources() - java

[英]getResources() for ImageIcon - java

我的第一个问题:

几天来我一直试图弄清楚这一点,但我到了失去耐心的地步。 以下是一些代码和我的项目结构。

问题:如何让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);
       }
   }

项目结构

通常,从 Eclipse 导出 JAR 文件时,导出src\/resources<\/code>的内容减去<\/em>src<\/code>路径名本身。 要从您的 JAR 中加载图像,您可以执行以下操作:

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

如果 png 文件已打包到 JAR 中与它们在原始 src 目录中相同的位置,则

XXX("resources/icons/xyz.png");

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