图像不会出现在 Jar 中 [英] Images Won't Appear In A Jar

查看:34
本文介绍了图像不会出现在 Jar 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I am making a basic text adventure game using Java, and I have decided to include images. The code I use to load my images onto the program is this:

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 时,没有任何图像出现.如果有人能帮我解决这个问题,我将不胜感激.谢谢!

When I run the program in eclipse everything works perfectly fine, but when I export it as a jar none of the images appear. If anyone could help me fix this I would greatly appreciate it. Thanks!

推荐答案

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

Be sure that your icon is included to the jar file, and try to find in runtime with a classloader. (Example below) Don't use any relative or absolute path just use the file name:

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

这篇关于图像不会出现在 Jar 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆