在任何地方我都看到有关使用FXMLLoader #setController()的解释,它与使用fx:root以及以编程方式设置根节点相关联(Oracle Docs和SO答案都有这种模式).这是一个要求吗?或者,我可以创建一些很好的旧集装箱定期FXML(可能使用SceneBuilder),并设置只编程后的控制器?
在FXML中:
<BorderPane fx:id="root" prefHeight="500.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" > </Borderpane>
Run Code Online (Sandbox Code Playgroud)
在某些代码中(可能是控制器):
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml_example2.fxml"));
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
Run Code Online (Sandbox Code Playgroud)
我不认为这是一项要求.我通过调整Oracle教程代码在我的Application类中看起来像这样工作:
@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();
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我已经以编程方式设置了我的ExampleController,而不是使用fx:controller="ExampleController"FXML,我没有必要设置id:root它.
顺便说一句,我非常喜欢这种方法,因为它更模仿MVF中使用WPF设置数据上下文,并进一步将视图与控制器分离.
| 归档时间: |
|
| 查看次数: |
7254 次 |
| 最近记录: |