首页 > 解决方案 > javafx中的initialize()是什么意思?

问题描述

我在我的项目中写了一些代码,我发现我应该把我的按钮监听器放在 中public void initialize(),否则我不能使用按钮。我不知道 javafx 中的 initialize() 是什么意思,为什么我不能将其更改为另一个方法名称?

这是我代码中的初始化方法,我没有实现 Initializable。那么这在 javafx 中是什么意思呢?

public void initialize() {
    weight_number1.setOnAction(e -> number(1));
    weight_number2.setOnAction(e -> number(2));
    weight_number3.setOnAction(e -> number(3));
    weight_number4.setOnAction(e -> number(4));
    weight_number5.setOnAction(e -> number(5));
    weight_number6.setOnAction(e -> number(6));
    weight_number7.setOnAction(e -> number(7));
    weight_number8.setOnAction(e -> number(8));
    weight_number9.setOnAction(e -> number(9));
    weight_number0.setOnAction(e -> number(0));
    weight_numberCE.setOnAction(e -> symbol(1));
    weight_numberLeft.setOnAction(e -> symbol(2));
    weight_numberp.setOnAction(e -> symbol(3));

    weight_box1.setOnAction((event) -> {
        change();
        showans();
    });
    weight_box2.setOnAction((event) -> {
        change();
        showans();
    });
}

标签: javafxinitialization

解决方案


The initialize() method is used to initialize any controls, especially when it is something that can't be done from the FXML. An example of this is setCellFactory() and setCellValueFactory(). If you have nothing to initialize, then you do not need to put an initialize() method in your controller class.

Some people thought that they could initialize in the controller class constructor, but that is the wrong place to initialize. This is because FXML injection only occurs after the controller class has been instantiated. FXML injection occurs just before initialize() is being called, which makes it safe to perform initialization in initialize(). Initializing in constructor will give you NullPointerException, if you used the reference of an injected control (e.g. @FXML private Button button).

In JavaFX 2.0, controller classes were required to implement the Initializable interface if the controller has anything to initialize. If you added initialize() without implementing the interface, no initialization will occur.

This was changed in JavaFX 8.0. Controller classes will no longer need to implement Initializable interface, but you may still choose to do so. The only thing to take note is that you need to add the @FXML annotation if the initialize() is non-public. If the initialize() method is public, then you can just skip the annotation.

I would recommend keeping the initialize() method private (or protected, which is rarely useful). Keeping initialize() private makes it less likely for initialization to occur more than once, which could potentially cause unexpected behavior.

Minor Update

In case you are wondering how initialize() gets called when it does not implement the Initializable interface, it is called via the use of Java Reflection. That is why you need to use the exact method name.


推荐阅读