简体   繁体   中英

Cannot communicate between controllers in JavaFX

I am trying to develop a demo app using JavaFX where I have 2 controllers MainController and AddUserController, each of them has its own .fxml file, main.fxml contains table that displays the list of users, and a button that opens the window for adding user with some fields. So the list of users is contained in a in-memory DB.

So when adding an user the table isn't filled with the list.

MainController.java

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

AddUserController.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();
}

After adding the user the table isn't updated, but if I try to usersTable.getItems(); the list is there, what's the problem so far?

// UPDATE:

Trying to execute this from MainController.java and it is working OK

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

The reason might be that you create a new controller on a new pane each time you handle an "add user" event. This is plainly wrong, as changes to it don't affect the pane which is actually displayed.

Instead, you should get the controller when you load your pane, store it somewhere and refer to it whenever you need it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM