Java 我的jar文件赢了';不加载图像

Java 我的jar文件赢了';不加载图像,java,jar,executable-jar,imageicon,Java,Jar,Executable Jar,Imageicon,我目前正在写一个程序,我需要把它作为一个罐子发送给一个朋友。该程序有图像,需要加载的程序正常工作,我希望它都包含在一个罐子。目前,它无法从可执行jar或通过命令行运行它。然而,它在netbeans中工作 以下是我使用的代码: protected ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = getClass().getClassLoader().getResource(pat

我目前正在写一个程序,我需要把它作为一个罐子发送给一个朋友。该程序有图像,需要加载的程序正常工作,我希望它都包含在一个罐子。目前,它无法从可执行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;
 }
}
要加载我正在使用的图像,请执行以下操作:

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文件是用包含类文件和资源文件夹的文件夹设置的,它们都位于jar文件的顶层

我到处寻找解决这个问题的方法,但我找不到任何有效的方法


谢谢

您的URL将计算为
“//resources/tiles/tile.png”
,这没有意义(但从NetBeans运行时使用的
类加载器可能会容忍此错误)。

尝试删除首字母
“/。/”
。此外,您不需要引用
File.separator
,因为字符串被视为一个相对URL,正斜杠始终有效。

尽管存在其他问题,但您的代码仍具有失败速度慢的不可取属性

试试像这样的东西

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

很抱歉设置了格式,但iPad太难做到正确。

使用
//resources/back\u img.png
,而不是使用
resources/back\u 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;
    }

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