Java: NullPointerException from class.getResource( … )

安稳与你 提交于 2019-11-28 01:16:40

I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.

Try the following:

getClass().getClassLoader().getResource("/icons/icon_prayer.png")

Or:

ClassLoader.getSystemResource("/icons/icon_prayer.png")

As far as I know getResource() will look into locations of known resources, in other words if the folder /icons/ is not seen as a resource folder it will not as you had expected. There are two ways of going around this as far as I know:

1) Set icons folder as a resource to the application, then you can use getResource() for instance URL css_url = getClass().getResource("/resource/style.css");

For more info on this option, see http://lj4newbies.blogspot.com/2008/03/using-classgetresource-load-resource.html

2) Get the icon as a regular file without using getResource() method. This is actually adviced in Swing tutorials on Sun/Oracle own documentation .

Generally, applications provide their own set of images used as part of the application, as is the case with the images used by many of our demos. You should use the Class getResource method to obtain the path to the image. This allows the application to verify that the image is available and to provide sensible error handling if it is not. When the image is not part of the application, getResource should not be used and the ImageIcon constructor is used directly. For example:

ImageIcon icon = new ImageIcon("images/middle.gif", "a pretty but meaningless splat");

Hope this helps, good luck!

Old thread but since I bumped into a similar problem just now...

I'm using Eclipse and I copied a file to the "resources" folder using system commands (cp). However, eclipse threw a NullPointerException because I didn't refresh the "resources" folder. So the file was there but Eclipse didn't see it.

So in Eclipse: "Package Explorer" -> "resources" -> Mouse right click -> refresh. This fixed it for me.

Valencia Starr

I added my music, images, etc to a folder added to the build path. Then I just used

URL url="CurrentClass".class.getClassLoader().getResource("media file name not the path");
setIconImage(new ImageIcon(url.getPath()).getImage());

to set the image icon.

The only thing that can throw a NullPointerException in this line of code is the first ., which means that prayerLevel is null.

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