Exported JAR Won't Read Image [duplicate]

2019-03-01 06:25发布

问题:

This question already has an answer here:

  • Accessing image paths in Eclipse 2 answers

I am attempting to get an image to show up in a JPanel. Here is the code I'm using:

        URL imageURL;
        BufferedImage image = null;
        ImageIcon icon;

        imageURL = getClass().getClassLoader().getResource("images/audiorpglogo.png");
        if (imageURL == null) {
            System.out.println(imageURL == null);
            try { imageURL = new File("images/audiorpglogo.png").toURI().toURL(); }
            catch (Exception e1) { imageURL = null; }
        }

        System.out.println(imageURL == null);

        try { image = ImageIO.read(imageURL); }
        catch (Exception e) { }

        System.out.println(image == null);

        icon = new ImageIcon(image);

        System.out.println(icon == null);

        logo = new JLabel(icon);

When I run this program in Eclipse, I get the following output:

true
false
false
false

However, when I export the program as a runnable JAR, I get this following output:

true
false
true
java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:204)
    at me.pogostick29.audiorpg.window.Window.<init>(Window.java:85)
    at me.pogostick29.audiorpg.window.WindowManager.setup(WindowManager.java:16)
    at me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:30)

Thanks in advance for the help!

回答1:

You should have a resource folder with the folder named images in that, then it should work.

Example:

How I access those icons:

public BufferedImage icon32 = loadBufferedImage("/icon/icon32.png");
public BufferedImage icon64 = loadBufferedImage("/icon/icon64.png");

private BufferedImage loadBufferedImage(String string)
{
    try
    {
        BufferedImage bi = ImageIO.read(this.getClass().getResource(string));
        return bi;
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}


回答2:

Try this code:

try { 
  InputStream in = getClass().getResource(imgName); //Read from an input stream 
  img = new ImageIcon(ImageIO.read(in));    
}catch (Exception e1) {
 e1.printStackTrace();
}