This question already has answers here:
Accessing image paths in Eclipse
                                
                                    (2个答案)
                                
                        
                                6年前关闭。
            
                    
我正在尝试使图像显示在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)


先谢谢您的帮助!

最佳答案

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

08-29 00:48