我目前正在编写一个程序,我需要将其发送给朋友作为罐子。该程序具有需要加载程序才能正常工作的图像,我希望所有图像都包含在一个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;
 }
}

对于URL,我也尝试过

 getClass().getResource(path)

应该创建图像的行是:

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

我的JAR文件是使用包含类文件和资源文件夹的文件夹设置的,均在其顶部级别上。

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

谢谢。

有帮助吗?

解决方案

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

其他提示

而不是使用 /./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;
    }

尽管如此,您的代码仍具有失败的可爱属性。

尝试类似的东西

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

对不起,格式化,但是iPad使它很难做到正确。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top