Java Swing ImageIcon, where to put images?
Asked Answered
S

3

8

I'm following this tutorial for java swing games: http://zetcode.com/tutorials/javagamestutorial/movingsprites/

At this point:

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

I just don't know what kind of path I have to write and where should I save my images (which directory).

Would you help me please? Would you give an example?

Suzan answered 28/7, 2013 at 19:35 Comment(3)
I learned alot of beginner Java from zetcode. When you get a chance you should check out this playlist on youtube: youtube.com/playlist?list=PL87AA2306844063D2 This helped me out alot too.Mydriatic
See also embedded-resource & info.Mincemeat
possible duplicate of Java in Eclipse: Where do I put files on the filesystem that I want to load using getResource? (e.g. images for an ImageIcon)Bunchy
M
16

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

Then use this:

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

If that doesn't work, try this:

ImageIcon(this.getClass().getResource("images/filename.png"));
Mydriatic answered 28/7, 2013 at 20:3 Comment(1)
1) Please use code formatting for code, input/output & structured documents like HTML or XML. To do that, select the sample and click the {} button above the messaged posting/editing form. 2) I would recommend the first form seen above. The 2nd form searches for the resource relative to the package of the class itself. So if the Java source file starts with package our.code; it will look for the image at /our/code/images/filename.png.Naashom
M
1
new ImageIcon(this.getClass().getResource());

This means that the image is present in the directory where the underlying class file is existing. So, you should save your image in the same directory where the class file of current java file will reside.

Myungmyxedema answered 28/7, 2013 at 19:40 Comment(0)
F
0

there is a mistake already in your code

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

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

ImageIcon ii = new
ImageIcon(getClass().getResource("/src/image/sample.png")); image iii=
ii.getImage();
Fanaticism answered 2/5, 2016 at 16:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.