图像无法在.jar文件中使用 [英] Images will not work in a .jar file
问题描述
创建应用程序的JAR时,不再显示应用程序中的图像。我们加载图片的代码示例如下:
When a JAR of an application is created, the images in the application no longer appear. An example of our code for loading images is:
ImageIcon placeHolder = new ImageIcon("src\\Cards\\hidden.png");
我们不知道为什么会这样。如果我们不将它压缩到JAR,应用程序将按预期运行;作为一个JAR,图像就会消失。我们还尝试使用URL而不是ImageIcons,但这只会导致程序根本无法运行。
We have no idea why this is happening. The application runs as expected if we do not compress it to a JAR; as a JAR, the images simply disappear. We also tried using URLs instead of ImageIcons, but that just causes the program not to run at all.
有什么想法吗?
编辑:我们将图像文件放入正确路径的JAR文件中,这不是问题。
We are putting the image files into our JAR file in the correct paths, so that's not the problem.
推荐答案
检查您正在呼叫的构造函数的API。传入的字符串是文件路径 - 当资源打包在JAR中时,文件系统上没有包含图像的文件,因此您不能再使用此构造函数。
Check the API for the constructor you're calling. The string you pass in is a file path - when the resources are packaged in a JAR, there is no file on the filesystem containing the image, so you can't use this constructor any more.
相反,您需要使用类加载器从流中加载资源,并将它们拉入字节数组:
Instead you'd need to load the resources from a stream, using the classloader, and pull them into a byte array:
byte[] buffer = new byte[IMAGE_MAX_SIZE];
InputStream imageStream = getClassLoader().getResourceAsStream("src\Cards\hidden.png");
imageStream.read(buffer, 0, IMAGE_MAX_SIZE);
ImageIcon placeHolder = new ImageIcon(buffer);
当然需要更多例外和边缘案件处理,但这是它的要点。
Needs more exception and edge-case handling, of course, but that's the gist of it.
这篇关于图像无法在.jar文件中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!