简体   繁体   中英

Can I set the value of a TextField in one scene from another scene, while both scenes are showing?

I'm trying to populate the TextField from a scene with the value selected in another scene.

So there's a scene (I'll call it parent scene) with a TextField and a button which opens another scene (I'll call it child scene). The child scene has a TableView which selected value I want to set to the parent scene's TextField. I know how to do this only if the scene with the TextField is not already opened, in my case the child scene's stage being setted as showAndWait. So I think I need to get the parent scene's stage and set it to the stage field in select() method below from the child controller.

// method from child controller, called when selecting a row from the tableview

public void select() throws IOException
    { 
        Class class = (Class)table.getSelectionModel().getSelectedItem();
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getClassLoader().getResource("parentStage.fxml"));
        Parent parent = loader.load();
        Stage stage = // here i need to pass the parent stage I think;
        stage.initModality(Modality.APPLICATION_MODAL);
        ParentController parentController = loader.getController();


        table.setOnMouseClicked(event -> {
            if(event.getClickCount()==2){

       parentController.setTextField(new TextField(class.getValue()));

         stage.setScene(new Scene(parent));// also, 
I think, here it should be passed the already opened parent scene 
             stage.show();
            ((Node)(event.getSource())).getScene().getWindow().hide();
                }  });

// this is the method for the button from parent scene that opens the child scene

 public void add() throws IOException
    {
     Parent parent = FXMLLoader.load(getClass().getClassLoader().getResource("childStage.fxml"));
        stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stageProdusNou.setScene(new Scene(parent));
        stageProdusNou.showAndWait();

    }

Thanks.

You can do this without any need to reload the base layout, by:

  • Creating an object from the second controller
  • Create a method in the second controller to init the passed textfield to a local one.
  • Pass your textfield to the second controller with the created object and method.
  • Update your textfield when action occur on the second controller.

This answer is a summarization of the codes and steps here .

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