JavaFX Communication Between Controllers

0
1088
Receive message in second window

When you begin with JavaFX, one problem you might come up with is the communication between different controllers to communicate between scenes. In this article, we will see how to properly communicate between two different controllers in JavaFX.

JavaFX Controller Communication Method

The solution here is to get the controller from FXMLLoader. We use JavaFX FXMLLoader for inflating fxml and loading new views. This loader has a method called getController(). getController method will return an instance of the controller corresponding to the view we are going to load.

In this example, we take input to a text field from the user. When a button is clicked, new window will be opened and we pass the typed text to new window.

Type message in first window
Receive message in second window

First Scene Controller

When the button actionBtn is clicked, a new window will be called which is the second scene window. We take the input from inputField textfield and pass it with transfer data.

public class Scene1Controller implements Initializable {

    @FXML
    private TextField inputField;
    @FXML
    private Button actionBtn;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //When button clicked, load window and pass data
        actionBtn.setOnAction(event -> {
            loadSceneAndSendMessage();
        });
    }
    
    private void loadSceneAndSendMessage() {
        try {
            //Load second scene
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/javafxcontrollercommunication/scene2/scene2.fxml"));
            Parent root = loader.load();
            
            //Get controller of scene2
            Scene2Controller scene2Controller = loader.getController();
            //Pass whatever data you want. You can have multiple method calls here
            scene2Controller.transferMessage(inputField.getText());

            //Show scene 2 in new window            
            Stage stage = new Stage();
            stage.setScene(new Scene(root));
            stage.setTitle("Second Window");
            stage.show();
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}

Second Scene Controller

This controller is really simple. You just have to write a method that accept the string. Once the string is received, we set that in the display textfield.

public class Scene2Controller {
    @FXML
    private TextField display;
    
    //Receive message from scene 1
    public void transferMessage(String message) {
        //Display the message
        display.setText(message);
    }
}

Watch another example on YouTube


You may also find following interesting:-

View in Github
[JavaFX communicate between scenes, JavaFX window communication. JavaFX share data between scenes]