Access controller in another controller class

2019-02-10 23:17发布

I have root layout containing 2 layouts: - OptionsPane - DrawArea

What i am trying is to access DrawAreaController in OptionsPaneController to call its draw method. Below is initialize method from OptionsPaneController:

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        newDragonButton.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                if(newDragonButton.getText().equals("Nowy")){
                    //do something
                }

                else{
                    newDragonButton.setText("Nowy");

                    FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/DrawArea.fxml"));
                    DrawAreaController dac = (DrawAreaController) loader.getController();
                    Dragon dragon = new Dragon(600, 300, 20, 2, 90, 270, colorChooser.getValue());
                    if(dac == null)
                        System.out.println("controller = null");
                    dac.drawDragon(dragon);
                }
            }
        });
    } 

Unfortunately dac is always null.

Is there any mistake in my code or is it impossible to load controller in another controller?

1条回答
The star\"
2楼-- · 2019-02-10 23:58

The controller is always null, because you never load the FXMLLoader.

The load() loads the fxml and instantiates the controller instance for you. If you do not use this method before getController(), it will always return null

FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/DrawArea.fxml"));
Parent root = loader.load();
DrawAreaController dac = (DrawAreaController) loader.getController();

You may or may not want to store the root of the FXML..

查看更多
登录 后发表回答