model-view-controller – JavaFX在没有控制器的fxml中包含fxml
我正在使用
javafx编写应用程序.
这是一个“多屏幕”应用程序,带有一个主菜单,可以从中切换场景. 我的场景在不同的fxml文件中定义. 因为我尝试使用mvc模式我没有在fxml文件中设置控制器,我在FXMLloader上使用setController. 一切都运行正常,但我在单独的控制器和单独的fxml文件中有onmen的mainmenu及其所有功能. 我试过了 <fx:include source="Menubar.fxml"/> 并为fxml文件创建了一个控制器,当我在fxml文件中设置控制器时,我无法编译源代码.如何为包含的fxml文件设置控制器? startpage.fxml获取其控制器“Startpage” FXMLLoader loader = new FXMLLoader(getClass().getResource("../fxml/startpage.fxml")); loader.setController(new Startpage(m)); Pane mainPane = loader.load(); startpage.fxml包含menubar.fxml,现在如何设置菜单栏控件的控制器?或者如何在每个其他控制器中轻松包含menubarController? 解决方法
我认为你需要在加载器中使用controllerFactory来实现你想要的东西.当您使用controllerFactory时,您在FXML文件中指定控制器的类名,但控制器工厂允许您控制如何映射到对象(因此您仍然可以构建它在模型中传递等).为FXMLLoader指定controllerFactory时,该工厂还用于为FXML文件中的任何< fx:include>创建控制器.
最后,请注意,您可以将包含的fxml文件的控制器注入“main”fxml文件,如“Nested controllers” section of the FXML documentation中所述. 所以如果startpage.fxml看起来像这样: <!-- imports etc --> <BorderPane fx:controller="com.example.Startpage" ... > <top> <fx:include source="Menubar.fxml" fx:id="menubar" /> </top> <!-- etc ... --> </BorderPane> 和Menubar.fxml看起来像 <!-- imports etc --> <MenuBar fx:controller="com.example.MenubarController" ... > <!-- etc... --> </MenuBar> 然后,您可以使用以下命令控制控制器类的实例化: FXMLLoader loader = new FXMLLoader(getClass().getResource("../fxml/startpage.fxml")); Model m = ... ; Startpage startpageController = new Startpage(m); MenubarController menubarController = new MenubarController(m); Callback<Class<?>,Object> controllerFactory = type -> { if (type == Startpage.class) { return startpageController ; } else if (type == MenubarController.class) { return menubarController ; } else { // default behavior for controllerFactory: try { return type.newInstance(); } catch (Exception exc) { exc.printStackTrace(); throw new RuntimeException(exc); // fatal,just bail... } } }; loader.setControllerFactory(controllerFactory); Pane mainPane = loader.load(); 现在,如果需要,您实际上已经在应用程序代码中引用了两个控制器,但您也可以这样做 public class Startpage { public final Model m ; // note the name of this field must be xController,// where x is the fx:id set on the <fx:include>: @FXML private final MenubarController menubarController ; public Startpage(Model m) { this.m = m ; } // ... } 因此主控制器现在具有对菜单栏控制器的引用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |