JavaFX FXML Parameter passing from Controller A to B and back

前端 未结 3 1359
再見小時候
再見小時候 2020-12-11 11:17

I want to create a controller based JavaFX GUI consisting of multiple controllers.

The task I can\'t accomplish is to pass parameters from one Scene to another AND b

3条回答
  •  爱一瞬间的悲伤
    2020-12-11 11:56

    There are numerous ways to do this.

    Here is one solution, which passes a Consumer to another controller. The other controller can invoke the consumer to accept the result once it has completed its work. The sample is based on the example code from an answer to the question that you linked.

    public Stage showCustomerDialog(Customer customer) {
      FXMLLoader loader = new FXMLLoader(
        getClass().getResource(
          "customerDialog.fxml"
        )
      );
    
      Stage stage = new Stage(StageStyle.DECORATED);
      stage.setScene(
        new Scene(
          (Pane) loader.load()
        )
      );
    
      Consumer onComplete = result -> {
        // update main screen based upon result.
      };
      CustomerDialogController controller = 
        loader.getController();
      controller.initData(customer, onComplete);
    
      stage.show();
    
      return stage;
    }
    
    ...
    
    class CustomerDialogController() {
      @FXML private Label customerName;
      private Consumer onComplete
      void initialize() {}
      void initData(Customer customer, Consumer onComplete) {
        customerName.setText(customer.getName());
        this.onComplete = onComplete;
      }
    
      @FXML
      void onSomeInteractionLikeCloseDialog(ActionEvent event) {
        onComplete.accept(new CustomerInteractionResult(someDataGatheredByDialog));
      }
    }
    

    Another way to do this is to add a result property to the controller of the dialog screen and interested invokers could listen to or retrieve the result property. A result property is how the in-built JavaFX dialogs work, so you would be essentially imitating some of that functionality.

    If you have a lot of this passing back and forth stuff going on, a shared dependency injection model based on something like Gluon Ignite, might assist you.

提交回复
热议问题