编程语言
首页 > 编程语言> > 超级初始化后,JavaFx调用超级方法

超级初始化后,JavaFx调用超级方法

作者:互联网

我有一个实现Initializable的类.

public abstract class ExampleClass implements Initializable {

    public void ExampleClass() {
        // Load FXML
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // Initialize stuff
    }

    public void afterInitialize() {
        // Do things that are reliant upon the FXML being loaded
    }
}

然后,我扩展这个抽象类:

public class ExampleSubclass extends ExampleClass {

    public ExampleSubclass() {
        super(/* real code has params */);
        this.afterInitialize(); // Problem here
    }
}

但是,当我调用afterInitialize()时,它的行为就像抽象类中的FXML尚未加载.这使我感到困惑,因为我先调用了super()构造函数,所以我认为FXML应该已经加载了.

我究竟做错了什么?

提前致谢.

解决方法:

根据这个answer,初始化方法的调用不会在构造函数中发生,而是在它之后发生.因此,当您在子类的构造函数中调用afterInitialize时,实际上是在初始化之前调用了它!

In a few words: The constructor is called first, then any @FXML
annotated fields are populated, then initialize() is called…

因此,在调用initialize时,所有FXML元素均已加载,并且如其他建议那样,您可以在initialize方法内部调用afterInitialize,但是如果您不想这样做,则可以使用@PostConstruct批注:

public abstract class ExampleClass implements Initializable {

    public void ExampleClass() {
        // Load FXML
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // Initialize stuff
    }

    @PostConstruct
    public void afterInitialize() {
        // Do things that are reliant upon the FXML being loaded
    }
}


public class ExampleSubclass extends ExampleClass {

    public ExampleSubclass() {
        super(/* real code has params */);
    }

    @PostConstruct
    @Override
    public void afterInitialize() {
         super.afterInitialize();
        // other things
    }
}

标签:javafx,initialization,fxml,super,java
来源: https://codeday.me/bug/20191112/2023810.html