使用fx:root是以编程方式设置控制器的必要条件吗



无论在哪里,我都能看到关于使用FXMLLoader#setController()的解释,它与使用fx:root以及以编程方式设置根节点有关(Oracle文档和SO答案都有这种模式)。这是要求吗?或者,我可以用一些好的旧容器创建一个常规的FXML(可能使用SceneBuilder),然后通过编程只设置控制器吗?

在FXML中:

<BorderPane fx:id="root" prefHeight="500.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" > </Borderpane>

在某些代码中(可能是控制器):

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml_example2.fxml"));
fxmlLoader.setController(this);
try {
fxmlLoader.load();            
} catch (IOException exception) {
throw new RuntimeException(exception);
}

我不认为这是一个要求。在我的应用程序类中,我通过调整Oracle教程代码来实现这一点

@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中更紧密地设置数据上下文,并进一步将视图与控制器解耦。

最新更新