无法在JavaFX中的控制器之间进行通信

时间:2016-07-15 08:28:28

标签: java javafx

我正在尝试使用JavaFX开发一个演示应用程序,其中我有2个控制器MainController和AddUserController,每个控制器都有自己的.fxml文件,main.fxml包含显示用户列表的表,以及一个打开用于添加某些字段的用户的窗口。因此,用户列表包含在内存数据库中。

因此,在添加用户时,表格未填充列表。

MainController.java

    ExitFlag = 2 
    Local minimum possible. Constraints satisfied. 
    fmincon stopped because the size of the current step is less than the selected value of the step size tolerance and constraints are  satisfied to within the selected value of the constraint tolerance. 

    ExitFlag = -2 
    No feasible solution found. 
    fmincon stopped because the size of the current step is less than the selected value of the step size tolerance but constraints are not satisfied to within the selected value of the constraint tolerance. 

AddUserController.java

    options=optimset('fmincon');
    options=optimset(options,...
                     'Algorithm','sqp',...
                     'ScaleProblem','obj-and-constr',...
                     'TypicalX',[3, 50, 3, 40, 50, 50],...
                     'TolX',1e-12,...%12
                     'TolFun',1e-8,...%6
                     'TolCon',1e-3,...%6
                     'MaxFunEvals',1000,...  %1000
                     'DiffMinChange',1e-10);

添加用户后,表格没有更新,但如果我尝试public void setTestUser(){ List<Users> users = new ArrayList(); Users user = new Users(); user.setName("Name"); user.setSurname("Surname"); users.add(user); name.setCellValueFactory(new PropertyValueFactory<Users, String>("name")); surname.setCellValueFactory(new PropertyValueFactory<Users, String>("surname")); usersTable.setItems(FXCollections.observableArrayList(users)); } 列表就在那里,到目前为止出现了什么问题?

//更新:

尝试从MainController.java执行此操作,它正常运行

private void handleAddUser(ActionEvent event) throws IOException {

    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.load(getClass().getResource("/fxml/main.fxml").openStream());
    MainController mainController = fxmlLoader.getController();

    Users user = new Users();
    user.setName(name.getText());
    user.setSurname(surname.getText());
    user.setDateOfBirth(dateOfBirth.getValue().toString());

    usersService.add(user);

    mainController.populateUsersTable();
}

1 个答案:

答案 0 :(得分:2)

原因可能是您每次处理&#34;添加用户&#34;时都会在新窗格上创建新控制器。事件。这显然是错误的,因为它的更改不会影响实际显示的窗格。

相反,您应该在加载窗格时获取控制器,将其存储在某个位置并在需要时随时引用它。

FXMLLoader myLoader = new FXMLLoader(
                getClass().getResource(screen.getFile()),
                resources);
Parent loadScreen = myLoader.load();
XYController myScreenController = myLoader.getController();