Java 访问.jar文件中的.png图像并使用它

Java 访问.jar文件中的.png图像并使用它,java,image,Java,Image,我有这段代码,但我不知道如何加载image stone.png以便使用它 package mine.mine.mine; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class MainGame { p

我有这段代码,但我不知道如何加载image stone.png以便使用它

package mine.mine.mine;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class MainGame {
    private static void showGUI()
    {   JFrame frame = new JFrame("Mine Mine Mine");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel emptyLabel = new JLabel("");
    emptyLabel.setPreferredSize(new Dimension(496, 496));
    frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    BufferedImage img = null, diamond = null, emerald = null, gold = null, lapis = null, iron = null, redstone = null, coal = null; //Ignore these.
    try {
        img = ImageIO.read(new File("stone.png")); //Main problem is here. Used debug method on line 27.
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "ERROR: The game has corrupted/missing files. Please redownload the game.", "Mine Mine Mine", JOptionPane.ERROR_MESSAGE);
        JOptionPane.showMessageDialog(null, e.getStackTrace());
    }



}
    public static void main(String args[]){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
            }
        });
    }


}
我想在JLabel或JFrame上显示stone.png,这是我第一次尝试,所以请不要叫我noob。;)

存储在Jar文件中的图像(或任何内容)不能像访问
文件那样进行访问,相反,您需要使用
类#getResource
,它将返回一个
URL
,API的许多部分都可以使用该URL来加载这些资源

如果API的一部分不接受
URL
,则可以使用
类#getResourcesAsStream
,它返回一个
InputStream

类似于

img = ImageIO.read(MainGame.class.getResource("stone.png"));
这假设
stone.png
是jar文件的默认/顶级目录,如果它位于子目录中,则需要指定jar文件根目录的完整路径

嘿,谢谢你,它工作了:)。您能帮助我在JLabel/JFrame上显示该图像吗?