JavaFX FXML 控制器 - 构造函数与初始化方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34785417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:59:29  来源:igfitidea点击:

JavaFX FXML controller - constructor vs initialize method

javajavafx

提问by mrbela

My Applicationclass looks like this:

我的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 FXMLLoadercreates an instance of the corresponding controller (given in the FXMLfile via fx:controller) by invoking first the default constructor and then the initializemethod:

FXMLLoader创建相应的控制器(在所给出的实例FXML经由文件fx:controller通过调用第一默认构造,然后)initialize方法:

public class MainViewController {

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

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

The output is:

输出是:

first
second

So, why does the initializemethod exist? What is the difference between using a constructor or the initializemethod to initialize the controller required things?

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

Thanks for your suggestions!

感谢您的建议!

采纳答案by Nikos Paraskevopoulos

In a few words: The constructor is called first, then any @FXMLannotated fields are populated, then initialize()is called. So the constructor does NOT have access to @FXMLfields referring to components defined in the .fxml file, while initialize()does have access to them.

简而言之:首先调用构造函数,然后@FXML填充任何带注释的字段,然后initialize()调用。因此,构造函数无权访问@FXML引用 .fxml 文件中定义的组件的字段,但initialize()可以访问它们。

Quoting from the Introduction to FXML:

引自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.

[...] 控制器可以定义一个 initialize() 方法,当相关文档的内容完全加载时,该方法将在实现控制器上调用一次 [...] 这允许实现类执行任何必要的发布- 处理内容。

回答by Itai

The initializemethod is called after all @FXMLannotated members have been injected. Suppose you have a table view you want to populate with data:

在注入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. 
    }
}

回答by gkhaos

In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializablefrom the fxml library.

除了上述答案之外,可能还应该指出,有一种传统的方式来实现初始化。fxml 库中有一个名为Initializable的接口。

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.getItems().addAll(getDataFromSource());
    }
}

Parameters:

参数:

location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized. 

And the note of the docs why the simple way of using @FXML public void initialize()works:

以及文档说明为什么简单的使用方法@FXML public void initialize()有效:

NOTEThis interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

NOTE此接口已被位置和资源属性自动注入控制器所取代。FXMLLoader 现在将自动调用由控制器定义的任何适当注释的无参数 initialize() 方法。建议尽可能使用注入方法。