Java Swing:显示 Jar 中的图像 [英] Java Swing: Displaying images from within a Jar
问题描述
从 Eclipse 运行 Java 应用程序时,我的 ImageIcon 显示正常.
When running a Java app from eclipse my ImageIcon shows up just fine.
但是在创建一个 jar 之后,图像的路径显然被搞砸了.
But after creating a jar the path to the image obviously gets screwed up.
有没有办法在运行时从 jar 中提取图像,以便我可以打开它?或者,有没有更好的方法来做到这一点?
Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this?
如果可能,我想分发单个 jar 文件.
I'd like to distribute a single jar file if possible.
推荐答案
要从加载代码的相同 jar 中的图像文件创建 ImageIcon
:
To create an ImageIcon
from an image file within the same jars your code is loaded:
new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg"))
Class.getResource
返回资源的 URL(或 null
!).ImageIcon
有一个从 URL 加载的构造函数.
Class.getResource
returns a URL of a resource (or null
!). ImageIcon
has a constructors that load from a URL.
要为不在类路径"上的 jar 中的资源构建 URL,请参阅 java.net.JarURLConnection
的文档.
To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection
.
这篇关于Java Swing:显示 Jar 中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!