Java 图片未在 Swing 中显示

Java Image not showing up in Swing

我制作了一个 JLabel,其图标是一个 ImageIcon,但它似乎无法被识别。

当我将它添加到项目根目录时,它会出现在我的 IDE 中,但在构建时它不会添加到 jar 文件中。

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class create {
    Random rand = new Random();
    int x = Toolkit.getDefaultToolkit().getScreenSize().width;
    int y = Toolkit.getDefaultToolkit().getScreenSize().height;
    public void CreateJFrame() {
        JFrame j = new JFrame("Test");
        j.setLocation(rand.nextInt(x), rand.nextInt(y));
        j.setPreferredSize(new Dimension(rand.nextInt(x), rand.nextInt(y)));
        j.setResizable(false);
        j.setLayout(new FlowLayout());
        j.pack();

        ImageIcon img = new ImageIcon("image.png"); // this file is in the resources folder and it is present in the jar file
        JLabel imgLabel = new JLabel(" ");
        imgLabel.setIcon(img);
        j.getContentPane().add(imgLabel);

        j.setVisible(true);

    }
}

使用此构造函数:new ImageIcon(ImageIO.read(create.class.getResourceAsStream("image.png")))。 您应该使用它,因为您无法从 jar 文件中获取文件,但您应该使用 InputStream 来读取(而不是写入)jar 文件中的文件。 除此之外,请确保您的图像位于 jar 文件主目录中,而不是子目录中。