【问题标题】:Exported JAR Won't Read Image [duplicate]导出的 JAR 不会读取图像 [重复]
【发布时间】:2013-04-14 04:44:44
【问题描述】:

我正在尝试让图像显示在 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)

提前感谢您的帮助!

【问题讨论】:

  • imageURL = getClass().getClassLoader().getResource("images/audiorpglogo.png"); 更改为 imageURL = getClass().getClassLoader().getResource("/images/audiorpglogo.png"); 并没有帮助。

标签: java image swing nullpointerexception


【解决方案1】:

您应该有一个资源文件夹,其中包含名为 images 的文件夹,那么它应该可以工作。

例子:

我如何访问这些图标:

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

【讨论】:

  • 我做到了,它成功了,但现在我遇到了这个烂摊子:icap.me/i/tZ43BrZ7fi.png
  • 大扫除时间到了(代码版)!
  • 那我该怎么办?我是否要创建一个音频文件夹,然后是一个 locs 子文件夹,然后将所有内容移入? (等)
  • 是的,我会创建一个audio 文件夹,然后将你所有的东西都移到其中。它可能很多(甚至有点杂乱无章),但如果你使用文件名按字母顺序对文件进行排序,你应该没问题。
【解决方案2】:

试试这个代码:

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

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 2016-07-10
    • 2021-08-13
    • 2013-06-15
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    相关资源
    最近更新 更多