导出的JAR无法读取图像

我试图让图像显示在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.(ImageIcon.java:204) at me.pogostick29.audiorpg.window.Window.(Window.java:85) at me.pogostick29.audiorpg.window.WindowManager.setup(WindowManager.java:16) at me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:30) 

在此先感谢您的帮助!

您应该有一个资源文件夹,其中包含名为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; } 

试试这段代码:

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