Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx Nested Controller

Tags:

javafx-2

I have tried this nested controller stuff over and over again, but it just doesn't work for me. I don't know why i can't get something as easy as this to work. I follow this example

<VBox fx:controller="com.foo.MainController">
  <fx:include fx:id="dialog" source="dialog.fxml"/>
  ...
</VBox>

public class MainController extends Controller {
  @FXML private Window dialog;
  @FXML private DialogController dialogController;

  ...
}

here is my code: app.Main.fxml

<AnchorPane prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
    <children>
        <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
        <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
        <fx:include source="InnerFile.fxml" fx:id="innerfile"/>
    </children>
</AnchorPane>

app.MainController.java

public class MainController {


    @FXML
    private Label label;
    @FXML
    private Button button;
    @FXML
    private InnerFileController controller;


    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        label.setText("Hello World!");


    }


    public void initialize() {
        controller.here(); 
    }


}

i'm calling a method of the nested controller ' controller.here(); ', and get a NullPointerExecption. I don't know what I have done wrong.

like image 692
blaze Avatar asked Jan 18 '26 10:01

blaze


1 Answers

The name of your variable for InnerFileController is incorrect. You have:

@FXML private InnerFileController controller;

but should be:

@FXML private InnerFileController innerfileController;

This is because the name of the variable for the controller of an included file is always the fx:id value with "Controller" added on to it.

like image 96
Jurgen Avatar answered Jan 21 '26 09:01

Jurgen



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!