Class.getResource() returns null

Assuming getClass() returns com.foo.bar.MyActionListener, getClass().getResource("img/foo.jpg") looks for a file named foo.jpg in the package com.foo.bar.img. If the image is not in this package, or if it is in this package but its root directory is not in the classpath, the method will return null.

If the img folder is at the root of the classpath, you should use getClass().getResource("/img/foo.jpg") (note the leading /), or getClass().getClassLoader().getResource("img/foo.jpg").

Leave a Comment