图像不会出现在jar子里

所以我正在使用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); }