导出的JAR无法读取图像

时间:2013-04-13 20:33:21

标签: java image swing nullpointerexception

我试图让图片显示在JPanel中。这是我正在使用的代码:

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

当我在Eclipse中运行此程序时,我得到以下输出:

true
false
false
false

但是,当我将程序导出为可运行的JAR时,我得到以下输出:

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)

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

你应该有一个资源文件夹,其中包含名为images的文件夹,然后它应该有效。

示例:

enter image description here

我如何访问这些图标:

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

答案 1 :(得分:0)

试试这段代码:

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