Where have I to put an image to use it to create a new Swing ImageIcon object?

时间秒杀一切 提交于 2019-12-02 06:35:12

With

ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));

You need to put the exit.png in the same package as the Class represented by getClass().

With

ImageIcon icon = new ImageIcon(getClass().getResource("/exit.png")); // note leading /

You need to put it at the root of your classpath. In Eclipse, that would happen by putting it directly in src.

The Class#getResource(String) javadoc states

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

Otherwise, the absolute name is of the following form:

modified_package_name/name Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

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