j will
j will

Reputation: 3807

Why am I getting a stackoverflow when loading my fxml?

I've adjusted my controller constructor and fxml so that all setup of the fxml to the controller is in the fxml except for the FXML construction and the fxml loading. Here is my controller:

public class MainOverviewTab extends Tab {

@FXML private AnchorPane content;

public MainOverviewTab() {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("main_overview_tab.fxml"));
    // fxmlLoader.setRoot(content);
    // fxmlLoader.setController(this);      

    try {
        fxmlLoader.load();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and my fxml file:

<AnchorPane id="AnchorPane" 
    fx:id="content" 
    fx:controller="dominion.application.controller.MainOverviewTab"
    ...other settings >

        <children>
            ....
        </children>
</AnchorPane>

The stackoverflow occurs when the fxmlLoader.load() is called and goes back to FXMLLoader fxmlLoader = new FXMLLoader(...) and then fxmlLoader.load() is called again... Why is this happening and how do I keep my controller constructor the same and load the fxml the same? Or is this not possible?

Upvotes: 1

Views: 1340

Answers (3)

Murali
Murali

Reputation: 339

You should not call FXml loader with in constructor. because when you load fxml file by using FXml loader , it will create MainOverviewTab again and again recursively. so it cause stack overflow error. If you remove the code from constructor and call from explicit method it will work.

public static void mainTabLoader() {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("main_overview_tab.fxml"));
    // fxmlLoader.setRoot(content);
    // fxmlLoader.setController(this);      

    try {
        fxmlLoader.load();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Upvotes: 1

Infernoz
Infernoz

Reputation: 125

This is what happens when a controller constructor tries to load FXML with a fx:controller attribute naming it, it get infinitely recursive. Been there... Clever use of fxmlLoader.setControllerFactory(factoryObject) can get around that.

See my answer for an FXML based control retaining fx:controller attribute in root element, this can be adapted for other controller creation.

Upvotes: 1

James_D
James_D

Reputation: 209663

If you call setController(...) on your FXMLLoader instance, you should not specify the controller in the FXML file. Remove the fx:controller attribute from the FXML file and uncomment the setRoot(...) and setController(...) calls and it should work.

Upvotes: 1

Related Questions