java fx fxml,JavaFX在没有控制器的fxml中包含fxml

我认为你需要在加载器中使用 controllerFactory 来实现你想要的东西 . 当您使用 controllerFactory 时,您在FXML文件中指定控制器的类名,但控制器工厂允许您控制如何映射到对象(因此您仍然可以构建它在模型中传递等) . 为 FXMLLoader 指定 controllerFactory 时,该工厂还用于为FXML文件中的任何 创建控制器 .

所以如果startpage.fxml看起来像这样:

和Menubar.fxml看起来像

然后,您可以使用以下命令控制控制器类的实例化:

FXMLLoader loader = new FXMLLoader(getClass().getResource("../fxml/startpage.fxml"));

Model m = ... ;

Startpage startpageController = new Startpage(m);

MenubarController menubarController = new MenubarController(m);

Callback, 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 :

@FXML

private final MenubarController menubarController ;

public Startpage(Model m) {

this.m = m ;

}

// ...

}

因此主控制器现在具有对菜单栏控制器的引用 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值