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.
推荐答案
要从同一个罐子中的图像文件中创建 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屋!