gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:51:47 25 4
gpt4 key购买 nike

我的 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 通过首先调用默认构造函数来创建相应 Controller 的实例(通过 fx:controllerFXML 文件中给出)然后是 initialize 方法:

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/34785417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com