Java Swing ImageIcon, where to put images?

房东的猫 提交于 2019-11-28 12:19:57
Steven

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"));

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

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.

Claude007

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!