j will j will - 1 month ago 39
Java Question

How to reference javafx fxml files in resource folder?

I am creating a javafx GUI application and my project is a maven configured project. I want to be able to reference my fxml files like this in my controllers:

FXMLLoader.load(getClass().getResource("main.fxml");


Where my main.fxml file is located in the src/main/resources folder and my controller is in the src/main/java folder. How do i go about doing this? My src/main/resources folder is in the build path and i am able to call a .properties file that is in the src/main/resources folder from a class in the src/main/java folder.

Edit

I attempted to place the fxml file in the corresponding directory of the main resources folder:

enter image description here

but i still got an error.

Answer

Example usage

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/main.fxml"));
Parent content = loader.load(); 

Location resolution options

  1. Put all of your fxml in the src/main/resources directory.

    loader.setLocation(getClass().getResource("/main.fxml"));
    
  2. Put all of your fxml in a src/main/resources/fxml directory.

    loader.setLocation(getClass().getResource("/fxml/main.fxml"));
    
  3. Place fxml in a corresponding resource directory; e.g. src/main/resources/com/mycompany/myapp.

    loader.setLocation(getClass().getResource("main.fxml")); 
    

The last option assumes that the class from which you are loading the fxml is in the same relative location in the corresponding Java source hierarchy, for example, you might invoke the last load command from source com.mycompany.myapp.Main.java.

Recommendations

I recommend instantiating an FXMLLoader via new FXMLLoader() rather than using the static methods on the FXMLLoader because there is an outstanding, though unactioned, request to deprecate the static FXMLLoader methods. The static methods become confusing when you want to get values (like instantiated controllers) out of a loader.

I also recommend setting the location on the instantiated FXMLLoader and just calling load() rather than rather than loading from a stream using load(stream).

To get the location, use getClass().getResource(), as it is URL based allowing for resolution of relative resources loaded in fxml and css files. getClass().getResourceAsStream() is stream based and does not allow for resolution of relative resources.

Comments