Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 295
haz Avatar asked Feb 21 '26 00:02

haz


1 Answers

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
    }
}
like image 62
Omid Avatar answered Feb 23 '26 13:02

Omid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!