Java Swing: Displaying images from within a Jar

后端 未结 5 1196
野趣味
野趣味 2020-11-22 15:13

When running a Java app from eclipse my ImageIcon shows up just fine.

But after creating a jar the path to the image obviously gets screwed up.

Is there a wa

5条回答
  •  有刺的猬
    2020-11-22 16:04

    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 returns a URL of a resource (or null!). ImageIcon has a constructors that load from a URL.

    To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection.

提交回复
热议问题