Joey
Joey

Reputation: 83

Javafx Injected Controller is null

When I try to use the controller I injected into my main controller, I always get a Nullpointer Exception (widgetlinebelowtableController is null). I have seen this answer, but did not help: JavaFX controller injection does not work

injected fxml:

    <HBox fx:id="widgetLineBelowTable" maxWidth="Infinity" spacing="5.0"   xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.widgets.WidgetLineBelowTableController">
        <padding>
            <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
        </padding>
        <Label fx:id="warningLabel" text="Overflow"/>
   </HBox>

The controller for this fxml:

public class WidgetLineBelowTableController
    {
    @FXML
    Label warningLabel;

    public void setColor(int r, int g, int b) {
        warningLabel.setTextFill(Color.rgb(r,g,b));
    }

}

My main fxml:

<VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1" stylesheets="/sample/style.css" fx:controller="sample.mainController">
    <fx:include source="/sample/menubar/MenuBar.fxml"/>
    <TabPane>

        <tabs>
            <Tab closable="false" text="FirstTab">
                <VBox>
                    <TitledPane collapsible="false">
                        <text>Results</text>
                        <fx:include source="table/Table.fxml"/>
                    </TitledPane>
                    <fx:include fx:id="widgetlinebelowtable" source="widgets/WidgetLineBelowTable.fxml" />
                </VBox>
            </Tab>
            <Tab closable="false" text="SecondTab">

            </Tab>
        </tabs>
    </TabPane>
</VBox>

The main controller:

import sample.widgets.WidgetLineBelowTableController;

public class mainController {

    @FXML
    private WidgetLineBelowTableController widgetlinebelowtableController;

    public mainController() {
        widgetlinebelowtableController.setColor(255,0,0);
    }

}

Thanks for the help.

Upvotes: 1

Views: 823

Answers (1)

James_D
James_D

Reputation: 209225

You are trying to access the injected field in the constructor, which obviously won't work (as the FXMLLoader cannot inject anything until the controller has been created, i.e. after the constructor executes).

Move the code to the initialize() method:

public class MainController {

    @FXML
    private WidgetLineBelowTableController widgetlinebelowtableController;

    public void initialize() {
        widgetlinebelowtableController.setColor(255,0,0);
    }

}

Also, please follow standard naming conventions

Upvotes: 1

Related Questions