我的 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:controller
在 FXML
文件中给出):
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()
可以访问它们。
[...] 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/