Javafx Nested Controller

2019-01-29 11:28发布

问题:

I have tried this nested controller stuff over and over again, It just doesn't work form 'me'. I don't know why i can get some thing as easy as this to. 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 nullpointerexecption. I don't know what have done wrong. Can some help me out please.

回答1:

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.



标签: javafx-2