繁体   English   中英

我的jar文件无法加载图像

[英]My jar file won't load images

我目前正在编写一个程序,需要以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文件设置为在其顶层包含类文件的文件夹和resource文件夹。

我一直在寻找解决此问题的方法,但是找不到任何有效的方法。

谢谢。

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

代替使用/./resources/back_img.png ,将resources/back_img.pngClassLoader resources/back_img.png使用。
这是示例:

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

无论如何,您的代码都具有令人难以抗拒的缓慢失败特性。

尝试类似

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

很抱歉格式化,但是iPad很难正确地进行格式化。

暂无
暂无

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

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