How to load icon from resource in Java?

Possible duplication (solved): stack overflow

I have icons (jpg, png) for my application, which are stored in my directory /var/tmp/gameXbox/src/image/<here> . Now, how can I use them in an application, not using a hard link, but as a resource?

Example: not working

 IconForMyButton = ImageIO.read(new File( ClassLoader.getSystemResourceAsStream("image/button1.png") )); 

enter image description here

It works when I make a hard link:

 IconForMyButton = ImageIO.read(new File( "/var/tmp/gameXbox/src/image/button1.png" )); 
+6
source share
3 answers

Resource loading occurs in the class path relative to the current package. If /var/tmp/gameXbox/src/ is in your class path, then:

 ImageIO.read( ClassLoader.getSystemResource( "image/button1.png" ) ); 

However, usually the src folder is not included in the classpath using the IDE. Try adding the image to the bin folder.

+9
source

I usually use class.getResource for this kind of operation:

 YourClass.class.getResource("image/button1.png") 

I use it to extract a file from a jar archive, but it should also work to extract from file system resources.

+4
source

Images do not fall into the source folder, but into the resource folder. Fix your IDE and use Maven and it will work with getResourceAsStream with the current classloader.

0
source

Source: https://habr.com/ru/post/904627/


All Articles