3

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.

haz
  • 2,034
  • 4
  • 28
  • 52
  • 2
    Why not calling `this.afterInitialize();` inside the `initialize(..,...);`? Only then you are soore that the FXML has been successfully loaded. Your question is interesting. – GOXR3PLUS Dec 02 '16 at 02:52
  • Typically that's what I'd do, but I need to pass parameters from `ExampleSubclass` to `afterInitialize()` (Probably should've specified that in the question, my bad) – haz Dec 02 '16 at 04:27
  • 1
    Actually the answer provided here is excellent , i din't even knew about `@PostConstruct` annotation. – GOXR3PLUS Dec 02 '16 at 04:28

1 Answers1

3

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
    }
}
Community
  • 1
  • 1
Omid
  • 5,823
  • 4
  • 41
  • 50