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?

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Dren Skywalker
  • 129
  • 1
  • 2
  • 10
  • I learned alot of beginner Java from zetcode. When you get a chance you should check out this playlist on youtube: http://youtube.com/playlist?list=PL87AA2306844063D2 This helped me out alot too. – Steven Jul 28 '13 at 20:28
  • See also [tag:embedded-resource] & [info](http://stackoverflow.com/tags/embedded-resource/info). – trashgod Jul 28 '13 at 22:39
  • 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)](http://stackoverflow.com/questions/270197/java-in-eclipse-where-do-i-put-files-on-the-filesystem-that-i-want-to-load-usin) – Barett Jun 24 '15 at 17:07

3 Answers3

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"));
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Steven
  • 833
  • 3
  • 11
  • 18
  • 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`. – Andrew Thompson Jul 29 '13 at 03:01
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.

Mac
  • 1,711
  • 3
  • 12
  • 26
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();
Iwo Kucharski
  • 3,735
  • 3
  • 50
  • 66