我的jar文件不会加载图片

时间:2011-01-13 00:35:14

标签: java jar executable-jar imageicon

我目前正在编写一个程序,我需要将其作为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文件是使用包含类文件和资源文件夹的文件夹设置在它的顶层。

我一直在寻找解决方法,但我找不到任何有用的方法。

感谢。

3 个答案:

答案 0 :(得分:2)

您的网址将评估为"/./resources/tiles/tile.png"这是没有意义的(但是从NetBeans运行时使用的ClassLoader可以容忍错误。)

尝试删除最初的"/./"。此外,您不需要引用File.separator,因为字符串被视为相对URL,正斜杠始终有效。

答案 1 :(得分:1)

不要使用/./resources/back_img.png,而是resources/back_img.png使用ClassLoader 这是一个例子:

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

答案 2 :(得分:0)

尽管如此,你的代码仍然具有失败缓慢的不可挽回的特性。

尝试类似

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

很抱歉格式化,但是iPad太难做了。

相关问题