我的 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);
}
}
The FXMLLoader
creates an instance of the corresponding controller (given in the FXML
file via fx:controller
) by invoking first the default constructor and then the initialize
方法:
public class MainViewController {
public MainViewController() {
System.out.println("first");
}
@FXML
public void initialize() {
System.out.println("second");
}
}
输出是:
first
second
那么,为什么存在 initialize
方法呢?使用构造函数或 initialize
方法初始化控制器所需的东西有什么区别?
感谢您的建议!
原文由 mrbela 发布,翻译遵循 CC BY-SA 4.0 许可协议
简而言之:首先调用构造函数,然后填充任何
@FXML
注释字段,然后调用initialize()
。这意味着构造函数 无权 访问
@FXML
引用 .fxml 文件中定义的组件的字段,而initialize()
确实 可以访问它们。引用 FXML 简介: