我的jar文件不会加载图片 [英] My jar file won't load images
问题描述
我目前正在编写一个程序,我需要将其作为jar发送给朋友。该程序有图像需要加载程序才能正常工作,我希望它们都包含在一个jar中。目前它不能从可执行jar或我通过命令行运行它。但它适用于netbeans。
这是我正在使用的代码:
要加载图像我'使用:
protected ImageIcon createImageIcon(String path,String description)
{
java.net。 URL imgURL = getClass()。getClassLoader()。getResource(path);
if(imgURL!= null)
{
返回新的ImageIcon(Toolkit.getDefaultToolkit()
.getImage(imgURL),description);
}
else
{
System.err.println(找不到文件:+路径);
返回null;
}
}
我刚试过的网址
getClass()。getResource(path)
应该创建图像的行是:
this.img = createImageIcon (File.separator +。+ File.separator
+resources+ File.separator +tiles+ File.separator +tile.png,tile);
我的jar文件设置为包含顶级的类文件和资源文件夹的文件夹我已经四处寻找解决方法,但我找不到任何有用的方法。
感谢。
您的网址将评估为/./ resources / tiles / tile.png
这没有意义(但是从NetBeans运行时使用的 ClassLoader
可以容忍错误。)
尝试删除最初的/./
。此外,您不需要对 File.separator
的引用,因为该字符串被视为相对URL并且正斜杠始终有效。
I am currently writing a program that I need to send to a friend as a jar. The program has images that need to be loaded for the program to work properly and I want it all to be contained in the one jar. Currently it doesn't work from the executable jar or when I run it through command line. It works in netbeans however.
Here's the code I'm using:
To load the image I'm using:
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;
}
}
for the URL I've also tried just
getClass().getResource(path)
The line where the image is supposed to be created is:
this.img =createImageIcon(File.separator+"."+File.separator
+"resources"+File.separator+"tiles"+File.separator+"tile.png","tile");
My jar file is setup with the folder containing the class files and the resource folder both on the top level of it.
I have searched around for ways to resolve this, but I cannot find anything that works.
Thanks.
Your URL will evaluate to "/./resources/tiles/tile.png"
which does not make sense (but maybe the ClassLoader
that is used when you run from NetBeans tolerates the error.)
Try dropping the initial "/./"
. Also you do not need the references to File.separator
as the string is treated as a relative URL and the forward slash is always valid.
这篇关于我的jar文件不会加载图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!