Java Swing ImageIcon, where to put images?

I follow this guide for java swing games: http://zetcode.com/tutorials/javagamestutorial/movingsprites/

In this moment:

ImageIcon ii = new ImageIcon(this.getClass().getResource()); image = ii.getImage(); 

I just don’t know which way I should write, and where I should save my images (which directory).

could you help me? Could you give an example?

+6
source share
4 answers

In your src folder, create a folder called "images" or "files", then place the image there.

Then use this:

 ImageIcon(this.getClass().getResource("/images/filename.png")); 

If this does not work, try the following:

 ImageIcon(this.getClass().getResource("images/filename.png")); 
+12
source

Read the Swing tutorial on How to use the icons for an example of loading images as a resource file:

+3
source
 new ImageIcon(this.getClass().getResource()); 

This means that the image is present in the directory in which the main class file is located. Thus, you should save your image in the same directory where the class file of the current java file will be stored.

0
source

there is an error in your code

 ImageIcon ii = new ImageIcon(this.getClass().getResource()); image = ii.getImage(); 

you already name ImageIcon ii, so you need to name the image now maybe iii then you create the image directory in src and you put your pic there, for example sample.png, the code will be

 ImageIcon ii = new ImageIcon(getClass().getResource("/src/image/sample.png")); image iii= ii.getImage(); 
0
source

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


All Articles