简体   繁体   中英

JavaFx call super method after super initialization

I have a class that implements 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
    }
}

I then extend this abstract class:

public class ExampleSubclass extends ExampleClass {

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

However when I call afterInitialize(), it behaves as though the FXML in the abstract class hasn't been loaded yet. This confuses me, as I call the super() constructor first, so I believe the FXML should have already been loaded.

What am I doing wrong?

Thanks in advance.

According to this answer , invocation of initialize method won't happen in the constructor, but after it. So when you call afterInitialize in subclass's constructor, it actually is called before initialize !

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

So when initialize is called all FXML elements are already loaded and as others suggested, you can call afterInitialize inside initialize method but if you don't want to do that, you can use @PostConstruct annotation:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM