Access controller in another controller class

丶灬走出姿态 提交于 2019-12-03 20:25:38

问题


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 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..



来源:https://stackoverflow.com/questions/33237356/access-controller-in-another-controller-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!