JAVAFX - 控制器之间共享对象

时间:2014-02-18 08:32:55

标签: object controller javafx share

请问如何在控制器之间共享对象用户?我有一个TabPanelController。在初始化中使用对象User发送到其他控制器数据。没问题,但是在显示阶段之前我无法访问此对象。

当在Stage之前加载控制器时,它可以在控制器中初始化方法中访问Stage吗?或者如何在加载器中处理onWindowShow(当windows显示时,对象用户被填充)?

    @FXML
    private ActionController panelActionController;
    @FXML
    private StoreController panelStoreController;
    @FXML
    private ProfilesController panelProfilesController;
    @FXML
    private UsersController panelUsersController;

    @FXML
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            menuUserInfo.setText("           " + loggedInUser.getName() + " " +
                    loggedInUser.getForname() + " (" + loggedInUser.getLogin() + ")");
            menuUserInfo.setUserData(loggedInUser);
            panelActionController.setLoggedUser(loggedInUser);
            panelStoreController.setLoggedUser(loggedInUser);
            panelProfilesController.setLoggedUser(loggedInUser);
            panelUsersController.setLoggedUser(loggedInUser);
        }
    });
    }

在panelActionController中

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    System.out.println(loggedInUser); // NULL..
}

当我按下舞台上的任何按钮时,loggedUser不为空。但是我需要在初始化期间按用户角色(管理员,用户)设置按钮,文本字段。

1 个答案:

答案 0 :(得分:0)

解决:

<强> 1。在主TabPanel控制器中注入控制器

fxml中的

必须有一个带有fx:id =“panelAction”的根元素(例如GridPane)。 控制器必须命名:fx:GridPane的id +字控制器: panelActionController

   @FXML
    private ActionController panelActionController;
    @FXML
    private StoreController panelStoreController;
    @FXML
    private ProfilesController panelProfilesController;
    @FXML
    private UsersController panelUsersController;

<强> 2。我在主TabPanelController中为所有子控制器编写getter:

    public ActionController getActionController() {
        return panelActionController;
    }

    public StoreController getStoreController() {
        return panelStoreController;
    }

    public ProfilesController getProfilesController() {
        return panelProfilesController;
    }

    public UsersController getUsersController() {
        return panelUsersController;
    }

第3。在主TabPanelStage(这里我有Object loggedInUser)获取所有控制器

TabPanelController tabPanelController = fxmlLoader.getController();

ActionController actionController = tabPanelController.getActionController();
StoreController storeController = tabPanelController.getStoreController();
ProfilesController profilesController = tabPanelController.getProfilesController();
UsersController usersController = tabPanelController.getUsersController();

<强> 4。然后:

actionController.setComponentsByRole(loggedInUser.getRole());