Domanda

I am trying to make a background for a java game. The code:

bg = new ImageIcon("src/sprites/bg.png").getImage();

works fine when I am in development, but once packaged into a jar, it doesn't seem to work. Also, if it helps, I am using eclipse.

È stato utile?

Soluzione

To create an ImageIcon from an image file within the same jar your code is loaded:

bg = new ImageIcon(getClass().getResource("/sprites/bg.png")).getImage();

Then put your image file in your classes directory instead of your "src" directory (e.g. "classes/sprites" in your case).

(duplicate of Java Swing: Displaying images from within a Jar)

Altri suggerimenti

To read it any resource from classpath, you need to provide the path relative to JAR starting with "/". Example, let's you have jar "test.jar" and inside that you have any class in com.test.package.Testing.class so to get this class as resource you need to use path

"/com/test/package.Testing.class"

You can always get a resource as stream which is loaded in JVM. For example you have bundled your image file in your jar which is in your classpath.

First get the input stream of image file as resource by using

Inputstream is = AnyClassWhichIsInSamejar.class.getClass().getResourceAsStream("/sprites/bg.png");

or

getClass().getResourceAsStream("/sprites/bg.png");

Now convert this input stream in your ImageIcon object

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top