My jar file won't load images

2019-03-02 20:15发布

问题:

I am currently writing a program that I need to send to a friend as a jar. The program has images that need to be loaded for the program to work properly and I want it all to be contained in the one jar. Currently it doesn't work from the executable jar or when I run it through command line. It works in netbeans however.

Here's the code I'm using:

To load the image I'm using:

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

for the URL I've also tried just

 getClass().getResource(path)

The line where the image is supposed to be created is:

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

My jar file is setup with the folder containing the class files and the resource folder both on the top level of it.

I have searched around for ways to resolve this, but I cannot find anything that works.

Thanks.

回答1:

Your URL will evaluate to "/./resources/tiles/tile.png" which does not make sense (but maybe the ClassLoader that is used when you run from NetBeans tolerates the error.)
Try dropping the initial "/./". Also you do not need the references to File.separator as the string is treated as a relative URL and the forward slash is always valid.



回答2:

Instead of using /./resources/back_img.png, use resources/back_img.png with ClassLoader.
Here is example :

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


回答3:

Despite anything else your code has the unenviable property of being fail-slow.

Try something like

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

Sorry for the formatting, but the iPad makes it too hard to do it right.