Can't load FXML in another package (JavaFX)

烈酒焚心 提交于 2019-11-28 02:28:10

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".

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!