Working with FXML loaders
There is only one class responsible for loading FXML—FXMLLoader
—but working with it requires care, as shown in the following sections.
Working with resources
Let's look again at loading FXML:
FXMLLoader.load(getClass().getResource("FirstDocument.fxml")); // URL
The load()
method's parameter here is a URL to the FXML file during runtime. It usually looks like the following:
jar:file:/path/to/jar/file/FxmlDemo.jar!/demo/FirstDocument.fxml
So, you will almost never set it directly as a String
but through the getResource()
method. The getResource
parameter can be relative to the current class, as in the preceding examples, or absolute to your JAR directory structure, for example:
FXMLLoader.load(getClass().getResource("/demo/FirstDocument.fxml"));
Using absolute paths allows you to store FXML files in a separate folder rather than among the Java code, which is more convenient for complex projects.
Often, the project structure will look like the following:
./src/demo/FirstController...