javafx-2 - 正在使用 fx :root a requirement to setting a controller programmatically?

标签 javafx-2 fxml

我到处都能看到关于使用 FXMLLoader#setController() 的解释,它与使用 fx:root 以及以编程方式设置根节点有关(Oracle DocsSO 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/

相关文章:

java - 如何在 JavaFX 中为图像的特定部分着色?

java - 在单元测试中等待 Platform.RunLater

javafx-2 - 水平 JavaFX 标题 Pane

将 fxml 加载节点添加为子节点时未应用 JavaFX 样式表

java - 将 Swing/FX 与绑定(bind)混合 - 使用自定义属性在线程之间进行调解?

java - 奇怪的 TableView.itemsProperty 行为?

java - 按下按钮时生成 'disappear'

java - 从 JavaFX 获取用户输入

JavaFX 标签不响应鼠标事件处理程序

checkbox - 在FXML中设置CheckBoxTableCell