图像不会出现在罐子里 [英] Images Won't Appear In A 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);
}
这篇关于图像不会出现在罐子里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!