【发布时间】:2011-06-08 05:14:15
【问题描述】:
我目前正在编写一个程序,我需要将它作为 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;
}
}
对于我也尝试过的网址
getClass().getResource(path)
应该创建图像的行是:
this.img =createImageIcon(File.separator+"."+File.separator
+"resources"+File.separator+"tiles"+File.separator+"tile.png","tile");
我的 jar 文件在其顶层设置了包含类文件和资源文件夹的文件夹。
我已经四处寻找解决此问题的方法,但找不到任何可行的方法。
谢谢。
【问题讨论】:
-
在您的“createImageIcon”函数中,您是否传入了要创建图像的文件名?因为如果是这种情况,则意味着文件被保存到 /./resources/tiles/tile.png”,相当于文件系统根级别的“/resources/tiles/tile.png”。在这种情况下,一旦您部署它,您的类路径就不会找到它。
-
如何使用 / 代替 File.separator 并使用“/resources/titles/tile.png”代替“/./resources/titles/tile.png”,这可能是不正确的路径,具体取决于在系统上
标签: java jar executable-jar imageicon