本文介绍了一个控制器到 2 个 fxmls (JavaFX)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将两个 FXML (JavaFX) 文件连接到一个控制器?我无法通过更改每个 FXML 文件中的fx:controller"来做到这一点......

有什么想法吗?

解决方案

是的,您可以这样做.虽然可以做到,我不推荐这种方法.

不要在任一 FXML 中放置 fx:controller 属性.创建一个新控制器并将相同的控制器设置为单独的 FXMLLoader 实例.

CustomerDialogController dialogController =新的 CustomerDialogController(param1, param2);FXMLLoader summaryloader = new FXMLLoader(getClass().getResource(customerSummary.fxml"));summaryLoader.setController(dialogController);窗格 summaryPane = (Pane) summaryLoader.load();FXMLLoader detailsLoader = new FXMLLoader(getClass().getResource(客户详细信息.fxml"));detailsLoader.setController(detailsController);窗格 detailsPane = (Pane) detailsLoader.load();SplitPane splitPane = new SplitPane(摘要窗格,详细信息窗格);

我想创建一个控制器,因为我在发送数据 beetwen 控制器时遇到问题

IMO 使用共享控制器来共享数据并不是解决此问题的首选解决方案.

相反,要么在多个控制器之间共享数据,有关示例,请参见:

这里还有一个例子:

Is possible to connect two FXML (JavaFX) files to one controller?I can't do this with changing "fx:controller" in each FXML file...

Any ideas?

解决方案

Yes, you can do this. Although, it can be done, I do not recommend this approach.

Don't place a fx:controller attribute in either FXML. Create a new controller and set the same controller into separate FXMLLoader instances.

CustomerDialogController dialogController =
    new CustomerDialogController(param1, param2);

FXMLLoader summaryloader = new FXMLLoader(
    getClass().getResource(
        "customerSummary.fxml"
    )
);
summaryLoader.setController(dialogController);
Pane summaryPane = (Pane) summaryLoader.load();

FXMLLoader detailsLoader = new FXMLLoader(
    getClass().getResource(
        "customerDetails.fxml"
    )
);
detailsLoader.setController(detailsController);
Pane detailsPane = (Pane) detailsLoader.load();

SplitPane splitPane = new SplitPane(
    summaryPane,
    detailsPane
);

IMO using a shared controller just to share data is not the preferred solution for this.

Instead, either share the data between multiple controllers, for examples of this see:

There is a further example here:

这篇关于一个控制器到 2 个 fxmls (JavaFX)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:40