我的jar文件不会加载图片
我目前正在编写一个程序,我需要将其作为jar发送给朋友。 该程序有图像需要加载程序才能正常工作,我希望它们都包含在一个jar中。 目前它不能从可执行jar或我通过命令行运行它。 然而,它适用于netbeans。
这是我正在使用的代码:
要加载我正在使用的图像:
protected ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = getClass().getClassLoader().getResource(path); if (imgURL != null) { return new ImageIcon(Toolkit.getDefaultToolkit() .getImage(imgURL),description); } else { System.err.println("Couldn't find file: " + path); return null; } }
对于URL我也尝试过
getClass().getResource(path)
应该创建图像的行是:
this.img =createImageIcon(File.separator+"."+File.separator +"resources"+File.separator+"tiles"+File.separator+"tile.png","tile");
我的jar文件是在包含类文件的文件夹和资源文件夹的顶层设置的。
我一直在寻找解决方法,但我找不到任何有效的方法。
谢谢。
您的URL将评估为"/./resources/tiles/tile.png"
,这是没有意义的(但是从NetBeans运行时使用的ClassLoader
可能容忍错误。)
尝试删除最初的"/./"
。 此外,您不需要对File.separator
的引用,因为该字符串被视为相对URL,并且正斜杠始终有效。
不使用/./resources/back_img.png
,而是使用resources/back_img.png
和ClassLoader
。
这是一个例子:
String path = "resources/back_img.png"; ClassLoader cl = ImageHandler.class.getClassLoader(); URL imgURL = cl.getResource(path); //URL imgURL = ImageHandler.class.getResource(path); if (imgURL != null) { ImageIcon icon = new ImageIcon(imgURL, description); Image img = icon.getImage(); Image sizedImg = img.getScaledInstance(width, height, Image.SCALE_DEFAULT); return new ImageIcon(sizedImg); } else { System.err.println("Couldn't find file: " + path); return null; }
尽管如此,你的代码仍然具有失败 – 缓慢的令人尴尬的特性。
尝试类似的东西
URL x = get class.getclassloader.getresource(...) If x == null Throw new defect "expected ... But it wasn't there"
对于格式化很抱歉,但是iPad太难做了。