gpt4 book ai didi

java - 图像不会出现在 jar 中

转载 作者:行者123 更新时间:2023-12-02 12:50:55 25 4
gpt4 key购买 nike

所以我正在使用 Java 制作一个基本的文本冒险游戏,并且我决定包含图像。我用来将图像加载到程序中的代码是这样的:

imagePanel = new JPanel();
imagePanel.setBounds(50, 50, 400, 260);
imagePanel.setBackground(Color.BLACK);
con.add(imagePanel);

imageLabel = new JLabel();

image = new ImageIcon(".//res//towngate.jpg");

imageLabel.setIcon(image);
imagePanel.add(imageLabel);

当我在 Eclipse 中运行该程序时,一切都工作得很好,但是当我将其导出为 jar 时,没有任何图像出现。如果有人能帮助我解决这个问题,我将不胜感激。谢谢!

最佳答案

确保您的图标包含在 jar 文件中,并尝试在运行时使用类加载器查找。 (下面的示例)不要使用任何相对或绝对路径,只需使用文件名:

public ImageIcon loadIcon(String iconName) throws IOException {
ClassLoader loader = this.getClass().getClassLoader();
BufferedImage icon =
ImageIO.read(loader.getResourceAsStream(iconName));
return new ImageIcon(icon);
}

关于java - 图像不会出现在 jar 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com