我到处都能看到关于使用 FXMLLoader#setController() 的解释,它与使用 fx:root 以及以编程方式设置根节点有关(Oracle Docs 和 SO answers 都有这种模式)。 这是一个要求吗?或者我可以使用一些好的旧容器创建一个常规 FXML(可能使用 SceneBuilder)并稍后以编程方式仅设置 Controller 吗?
在 FXML 中:
<BorderPane fx:id="root" prefHeight="500.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" > </Borderpane>
在一些代码中(可能是一个 Controller ):
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml_example2.fxml"));
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
最佳答案
我认为这不是必需的。我通过调整 Oracle tutorial code 来完成这项工作在我的应用程序类中看起来像这样:
@Override
public void start(Stage stage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml_example.fxml"));
fxmlLoader.setController(new ExampleController());
Parent root = (Parent)fxmlLoader.load();
stage.setTitle("FXML Welcome");
stage.setScene(new Scene(root, 300, 275));
stage.show();
}
如您所见,我以编程方式设置了我的 ExampleController,而不是使用 FXML 中的 fx:controller="ExampleController"
,而且我不必设置 id:root
任何地方都可以做到。
顺便说一句,我非常喜欢这种方法,因为它更接近于使用 WPF 在 MVVM 中设置数据上下文,并进一步将 View 与 Controller 分离。
关于javafx-2 - 正在使用 fx :root a requirement to setting a controller programmatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13617007/