【问题标题】:getResources() for ImageIcon - javaImageIcon 的 getResources() - java
【发布时间】:2012-12-31 18:12:02
【问题描述】:

我的第一个问题:

这几天我一直在尝试解决这个问题,但我到了失去耐心的地步。 以下是一些代码和我的项目结构。

问题:我怎样才能让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);
       }
   }

【问题讨论】:

    标签: java imageicon


    【解决方案1】:

    通常在从 Eclipse 导出 JAR 文件时,src/resources 的内容会被导出减去 src 路径名本身。要从您的 JAR 中加载图像,您可以这样做:

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

    确定的一种方法是检查:

    jar tvf yourjar.jar
    

    【讨论】:

      【解决方案2】:

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

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

      应该会产生正确的结果。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-03
          • 2012-11-27
          • 2013-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多