JavaFX FXML Controller - 构造函数与初始化方法

标签 java javafx

我的 Application 类如下所示:

public class Test extends Application {

    private static Logger logger = LogManager.getRootLogger();

    @Override
    public void start(Stage primaryStage) throws Exception {

        String resourcePath = "/resources/fxml/MainView.fxml";
        URL location = getClass().getResource(resourcePath);
        FXMLLoader fxmlLoader = new FXMLLoader(location);

        Scene scene = new Scene(fxmlLoader.load(), 500, 500);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

FXMLLoader 通过首先调用默认构造函数,然后调用 initialize 方法来创建相应 Controller 的实例(通过 fx:controllerFXML 文件中给出):

public class MainViewController {

    public MainViewController() {
        System.out.println("first");
    }

    @FXML
    public void initialize() {
        System.out.println("second");
    }
}

输出为:

first
second

那么,为什么会有initialize方法存在呢?使用构造函数或 initialize 方法来初始化 Controller 所需的东西有什么区别?

感谢您的建议!

最佳答案

简而言之:首先调用构造函数,然后填充任何 @FXML 注解字段,然后调用 initialize()

这意味着构造函数无法访问引用 .fxml 文件中定义的组件的 @FXML 字段,而 initialize() 可以访问它们。

引自Introduction to FXML :

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

关于JavaFX FXML Controller - 构造函数与初始化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48532394/

相关文章:

java - 播放所选目录中的 MP3 文件

JavaFx 相当于 Swing JFrame

java - 将进度信息从可调用对象传播到任务

java - 模拟特定类对象 stub 失败的测试mockito

java - 微调 Java 同步块(synchronized block)行为

java - 在android中加载和保存数据文件

java - 如何在解析为 dto 之前获取 http Jersey 响应状态?

java - 可以添加类(class)吗?

JavaFX 脚本和 Java

applet - 是否可以在 JavaFX 应用程序(桌面)中使用现有的 Applet