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:
but i still got an error.
Open your resources folder in the file explorer of your operation system. Here you will see that you have created a "dominion.application" folder instead of an "application" folder inside of a "dominion" folder. Because of this the "MainController" class is placed in a different package as the fxml file.
You are using
FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource("main.fxml") );
to load your main.fxml. This requires the main.fxml and the java class loading it in same directory/path. If you want to load an fxml file from a path/location different from the java class loading it, you need to use relative path. As @jewelsea mentioned above, you may use the relative path using / character before your main.fxml. So the code that will make it work for you in your case isExample usage
Location resolution options
Put all of your fxml in the src/main/resources directory.
Put all of your fxml in a src/main/resources/fxml directory.
Place fxml in a corresponding resource directory; e.g. src/main/resources/com/mycompany/myapp.
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
.FXMLLoader usage recommendations
Instantiate an FXMLLoader via
new FXMLLoader()
rather than using the static methods on the FXMLLoader.Set the location on the instantiated FXMLLoader and call
load()
rather than loading from a stream usingload(stream)
.To derive a location based upon a class, use
getClass().getResource()
, as it is URL based, rather thangetClass().getResourceAsStream()
which is stream based.IDE and Build Settings
Ensure that your IDE or build tool is copying the fxml files from the resource directory to the build output directory. For understanding Intellij settings for this, see: How to convert a normal java project in intellij into a JavaFx project.