另一个控制器类中的访问控制器 [英] Access controller in another controller class

查看:74
本文介绍了另一个控制器类中的访问控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的根布局包含2种布局:
-OptionsPane
-DrawArea

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

我正在尝试在OptionsPaneController中访问DrawAreaController进行调用它的绘制方法。下面是OptionsPaneController中的初始化方法:

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);
                }
            }
        });
    } 

不幸的是dac始终为空。

Unfortunately dac is always null.

我的代码中是否存在任何错误,或者是否不可能在另一个控制器中加载控制器?

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

推荐答案

该控制器始终为null,因为您从不加载FXMLLoader。

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

load() 加载fxml并为您实例化控制器实例。如果在 getController()之前不使用此方法,它将始终返回 null

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();

您可能会或可能不想存储FXML的根。

这篇关于另一个控制器类中的访问控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆