在阶段之间传递值 (JavaFx) (Eclipse)

Passing Value between Stage (JavaFx) (Eclipse)

我有两个 .fxml 和两个控制器。

一开始会显示访客信息(蓝色),只要点击“添加”按钮,就会弹出另一个阶段(grey/white)搜索ICnumber的访客。

我的计划是当我搜索完客人(灰色)后,我会点击“添加客人”按钮,阶段(灰色)将关闭,所有值将传递给客人信息(蓝色)。

    @FXML //Guest Information (blue stage)
void addGuest(ActionEvent event) throws IOException {
    iclb.setText("ok"); //ignore this
    
    Parent root = FXMLLoader.load(getClass().getResource("Guest.fxml"));

    Scene scene = new Scene(root);

    Stage stage = new Stage();
    stage.setScene(scene);
    stage.setTitle("Hotel System - Guest Information");
    stage.setResizable(false);
    stage.show();
}

public void addGuestInfo(String icno) {
    iclb.setText(icno); // this is the label for IC Number
}

--

    @FXML //Search Guest (grey stage)
void addGuest(ActionEvent event) throws IOException {
    
    FXMLLoader loader = new FXMLLoader(getClass().getResource("MenuDraft.fxml"));

    Parent root = loader.load();
    MenuController menu = loader.getController();
    menu.addGuestInfo(ictf.getText());

    Stage stage = (Stage) addbt.getScene().getWindow();
    stage.close();
}

到目前为止,我设法搜索了一位访客并能够通过单击“添加访客”按钮关闭灰色阶段,但这些值并未传递到访客信息(蓝色阶段)。

我是 Javafx 的新手...任何人都可以帮助我吗?

在您的第二个(“灰色”)控制器中,您可以这样做:

public class AddGuestController {

    // I assume you have a Guest class to encapsulate the data in the form
    private Guest guest = null ;
    public Guest getGuest() {
        return guest ;
    }

    @FXML
    private void addGuest(ActionEvent event) {
        guest = new Guest( /* data from form controls... */ );
        addbt.getScene().getWindow().hide();
    }
}

然后回到第一个(“蓝色”)控制器,您可以使用 stage.showAndWait() 阻止执行直到 window 关闭,并检查是否创建了访客:

@FXML //Guest Information (blue stage)
private void addGuest(ActionEvent event) throws IOException {
    
    FXMLLoader loader = new FXMLLoader(getClass().getResource("Guest.fxml"));
    Parent root = loader.load();

    Scene scene = new Scene(root);

    Stage stage = new Stage();
    stage.setScene(scene);
    stage.setTitle("Hotel System - Guest Information");
    stage.setResizable(false);
    stage.showAndWait();

    AddGuestController controller = loader.getController();
    Guest guest = controller.getGuest();
    if (guest != null) {
        // update view from guest:

        iclb.setText(guest.getIcNumber();
        // etc. 
    }
}