GetResource method doesn't work everywhere

Hi I got a problem with the "getResource" method.

new Object() {}.getClass().getResource("layout/main.fxml")

I’m trying to get a resources file from the layout directory but it always returns null when I’m using it in a subdirectory located file. (ResourcesUtils.java – see images)

It only works when I’m using it in the Main.java which is not in a subdirectory.

My project directory

Do I need to set a different path ?

Thanks for the help

Asked on July 16, 2020 in Java.
Add Comment
1 Answer(s)

layout/main.fxml is a "relative path." To get the concrete path, the system adds the path for the package of the class on which you’re calling getResource, which will be whatever package the code is in since you’re calling getResource on an anonymous local class .

The absolute path will work no matter where the code is located:

getResource("/fr/etna/penelope/layout/main.fxml") 

Another solution may be to call getResource on a specific class instead of an anonymous class, since this will use a fixed package name. For example:

Main.class.getResource("layout/main.fxml") 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.