【问题标题】:My jar file won't load images我的 jar 文件不会加载图像
【发布时间】:2011-06-08 05:14:15
【问题描述】:

我目前正在编写一个程序,我需要将它作为 jar 发送给朋友。该程序具有需要加载的图像才能使程序正常工作,我希望它们都包含在一个 jar 中。目前它不适用于可执行 jar 或当我通过命令行运行它时。但是它可以在 netbeans 中使用。

这是我正在使用的代码:

要加载我正在使用的图像:

protected ImageIcon createImageIcon(String path, String description)
{
 java.net.URL imgURL = getClass().getClassLoader().getResource(path);
 if (imgURL != null)
 {
     return new ImageIcon(Toolkit.getDefaultToolkit()
                  .getImage(imgURL),description);
 }
 else
 {
     System.err.println("Couldn't find file: " + path);
     return null;
 }
}

对于我也尝试过的网址

 getClass().getResource(path)

应该创建图像的行是:

this.img =createImageIcon(File.separator+"."+File.separator
           +"resources"+File.separator+"tiles"+File.separator+"tile.png","tile");

我的 jar 文件在其顶层设置了包含类文件和资源文件夹的文件夹。

我已经四处寻找解决此问题的方法,但找不到任何可行的方法。

谢谢。

【问题讨论】:

  • 在您的“createImageIcon”函数中,您是否传入了要创建图像的文件名?因为如果是这种情况,则意味着文件被保存到 /./resources/tiles/tile.png”,相当于文件系统根级别的“/resources/tiles/tile.png”。在这种情况下,一旦您部署它,您的类路径就不会找到它。
  • 如何使用 / 代替 File.separator 并使用“/resources/titles/tile.png”代替“/./resources/titles/tile.png”,这可能是不正确的路径,具体取决于在系统上

标签: java jar executable-jar imageicon


【解决方案1】:

您的 URL 将评估为 "/./resources/tiles/tile.png",这没有任何意义(但您从 NetBeans 运行时使用的 ClassLoader 可能会容忍错误。)
尝试删除最初的"/./"。此外,您不需要对 File.separator 的引用,因为字符串被视为相对 URL,并且正斜杠始终有效。

【讨论】:

    【解决方案2】:

    尽管你的代码具有失败缓慢这一令人羡慕的特性。

    试试类似的东西

    URL x = get class.getclassloader.getresource(...)
    If x == null
       Throw new defect "expected ... But it wasn't there"
    

    抱歉格式化,但 iPad 很难做到这一点。

    【讨论】:

      【解决方案3】:

      不要使用/./resources/back_img.png,而是使用resources/back_img.pngClassLoader
      这是示例:

          String path = "resources/back_img.png";
          ClassLoader cl = ImageHandler.class.getClassLoader();
          URL imgURL = cl.getResource(path);
          //URL imgURL = ImageHandler.class.getResource(path);
      
          if (imgURL != null) {
              ImageIcon icon = new ImageIcon(imgURL, description);
              Image img = icon.getImage();
              Image sizedImg = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
              return new ImageIcon(sizedImg);
          } else {
              System.err.println("Couldn't find file: " + path);
              return null;
          }
      

      【讨论】:

        猜你喜欢
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 2013-09-04
        • 1970-01-01
        • 1970-01-01
        • 2017-05-02
        • 2021-08-06
        相关资源
        最近更新 更多