Java Swing ImageIcon, where to put images?

2019-01-19 19:45发布

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?

4条回答
手持菜刀,她持情操
2楼-- · 2019-01-19 20:05

Read the Swing tutorial on How to Use Icons for examples of loading images as a resource file:

查看更多
够拽才男人
3楼-- · 2019-01-19 20:06

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();
查看更多
地球回转人心会变
4楼-- · 2019-01-19 20:07
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.

查看更多
太酷不给撩
5楼-- · 2019-01-19 20:24

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"));
查看更多
登录 后发表回答