For some reason I\'m getting an error when I try to load an FXML which is in a different package:
MainApp.java\"
FXMLLoader loader =
I can tell you what works for me. Firstly, the FXML files should be considered resources rather than Java source files, so they're best placed into their own directory tree. Your source code is currently living in the /src/main/java
tree, so your FXML files should be moved into the /src/main/resources
tree, ideally into a subdirectory called fxml
. (I also have a subdirectory called i18n
which holds the resource bundles to define text labels in multiple languages.)
Once your FXML files are found under the path /src/main/resources/fxml
you should be able to load them from your JavaFX controllers with something like this:
FXMLLoader loader = new FXMLLoader();
URL fxmlLocation = getClass().getResource("/fxml/main_screen.fxml");
loader.setLocation(fxmlLocation);
loader.setController(mainScreenController);
loader.setResources(ResourceBundle.getBundle("i18n/Text", new Locale("sv", "SE")));
Pane pane = loader.<Pane>load();
Scene scene = new Scene(pane);
(If the root element of your FXML file does not represent a Pane
then you'll need to modify the line which calls the load()
method, and replace Pane
with the appropriate type.)
Note that the call to getResource(String)
takes a path which begins with a forward-slash, and that represents the resource path root /src/main/resources/
.
And also note that, bizarrely, the call to getBundle(String)
does not start with a forward-slash, even though you're targeting exactly the same /src/main/resources/
path. I have to admit I can't explain why these two methods need to be treated slightly differently like this, but this code works to load both the "main_screen.fxml" file and the Swedish language resource bundle file "Text_sv_SE.properties".
Another thing to try for anyone experiencing this is to make sure that your fxml file is not empty. Open it in scenebuilder and drag an Anchor pane. That is what worked for me