JavaFX FXML控制器-構(gòu)造函數(shù)VS初始化方法我的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);
}}這個(gè)FXMLLoader創(chuàng)建相應(yīng)控制器的實(shí)例(在FXML文件通過fx:controller)首先調(diào)用默認(rèn)構(gòu)造函數(shù),然后調(diào)用initialize方法:public class MainViewController {
public MainViewController() {
System.out.println("first");
}
@FXML
public void initialize() {
System.out.println("second");
}}產(chǎn)出如下:first
second那么,為什么initialize方法存在嗎?使用構(gòu)造函數(shù)與initialize方法來初始化控制器所需的東西?謝謝你的建議!
3 回答

HUWWW
TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
@FXML
initialize()
@FXML
initialize()
[.]控制器可以定義一個(gè)初始化()方法,當(dāng)相關(guān)文檔的內(nèi)容完全加載時(shí),該方法將在實(shí)現(xiàn)控制器上調(diào)用一次[.]這允許實(shí)現(xiàn)類對(duì)內(nèi)容執(zhí)行任何必要的后處理。

翻翻過去那場(chǎng)雪
TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
initialize
@FXML
class MyController { @FXML TableView<MyModel> tableView; public MyController() { tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. } @FXML public void initialize() { tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. }}
添加回答
舉報(bào)
0/150
提交
取消