Skip to content
Advertisement

Intellij can’t read images in resources subfolder

So I have a maven project in intellij and I want to load images from the resources folder. It works perfectly for files that are directly in resources/. However, files that are in subfolder (for example resources/images/) are not found.

In this example, logo.png is correctly loaded while logo1.png is not found :

JavaScript

I could put all my files directly in resources, but it would be all disorganized…

Here’s the error I get when loading images/logo.png :

JavaScript

Advertisement

Answer

var img2 = new Image("logo1.png");

This code is just wrong, that’s not how you load resources.

This is how you do it:

JavaScript

The new Image(string) constructor takes as argument a URL, and logo1.png is not one of those.

In particular you are looking to load images from the exact same place java is loading your app’s class files, which is done with someClassInstanceThatIsUsedForContext.getResource. The best context to use is no doubt the class you’re in, hence, TheClassYouAreIn.class, which gets you that class instance. The getResource method returns a URL.

Note that the above construct is using relative paths: That code will look for a resource named logo1.png in the same place that TheClassThisCodeIsIn.class is located, even if it is in a jar file, dynamically created, or loaded over the network. In other words, if you have:

JavaScript

Then MyApp.class.getResource("hello.png") will look for com/foo/sashimisAwesomeApp/hello.png, because the class file for MyApp is at com/foo/sashimisAwesomeApp/MyApp.class. This means you need to match the package structure (That com/foo/sashimisAwesomeApp part) in your resource folder in your project directory structure. If you prefer to go from the ‘root’ of resources, include a leading slash: MyApp.class.getResource("/images/icon.png") will look in /images/icon.png in the jar file that also contains /com/foo/sashimisAwesomeApp/MyApp.class.

NB: Sidenote to the author of javafx’s Image class: Geez, what a disaster. That API should obviously have taken in a URL or URI or have a static constructor to load off of classpath instead of this mess.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement