【问题标题】:Images Won't Appear In A Jar图像不会出现在罐子中
【发布时间】:2017-11-20 21:01:29
【问题描述】:

所以我正在使用 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 中的对象不是文件,因此您不能使用 ImageIcon 构造函数的文件名形式来访问它们。看到类似this question

标签: java eclipse image jar


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2013-03-31
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多