JavaFX:从运行时加载的模态获取数据

JavaFX: Get data from modal loaded at runtime

我有一个模态 class:

public class DialogModal
{
    private String fxmlURL;
    private int width;
    private int height;

    public DialogModal( String url, int w, int h )
    {
        fxmlURL = url;
        width = w;
        height = h;
    }

    public void showDialogModal(Button root) throws IOException
    {
        Stage modalDialog = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource( fxmlURL ));
        Parent modalDialogRoot = loader.load();
        Scene modalScene = new Scene( modalDialogRoot, width, height );
        modalScene.getStylesheets().add(InventoryManager.class.getResource("InventoryManager.css").toExternalForm());
        modalDialog.initOwner(root.getScene().getWindow());
        modalDialog.setScene(modalScene);
        modalDialog.setResizable(false);
        modalDialog.showAndWait();
    }
}

然后这样打开(从 FXML 控制器):

    @FXML
    private void handleModalButton(ActionEvent e) throws IOException
    {
        DialogModal modal = new DialogModal("Modal.fxml", 400, 450);
        modal.showDialogModal((Button)e.getSource());
    }

我的问题是,如何将数据从模态(即 TextFields)返回到我的 handleModalButton 方法?这个modal可以给不同的FXML文件,所以它returns的数据可能不一样。

此外,我如何(或应该)将数据发送到 模态(例如,填充 TextFields)?

谢谢!

您可以使 DialogModal.showDialogModal() return 生成的模态对话框的控制器 window。

public <T> T showDialogModal(Button root) throws IOException
{
    Stage modalDialog = new Stage();
    FXMLLoader loader = new FXMLLoader(getClass().getResource( fxmlURL ));
    Parent modalDialogRoot = loader.load();
    T controller = loader.getController(); // Retrieve the controller
    Scene modalScene = new Scene( modalDialogRoot, width, height );
    modalScene.getStylesheets().add(InventoryManager.class.getResource("InventoryManager.css").toExternalForm());
    modalDialog.initOwner(root.getScene().getWindow());
    modalDialog.setScene(modalScene);
    modalDialog.setResizable(false);

    // You need Platform.runLater() so that this method doesn't get blocked
    Platform.runLater(() -> modalDialog.showAndWait());

    return controller; // Return the controller back to caller
}

然后在你的调用方法中:

@FXML
private void handleModalButton(ActionEvent e) throws IOException
{
    DialogModal modal = new DialogModal("Modal.fxml", 400, 450);
    FooController controller = modal.showDialogModal((Button)e.getSource());

    String data1 = controller.getTextField1Data();
    // ...
}

您需要确切知道 handleModalButton() 中控制器的 class,否则您将得到一个 ClassCastException。当然,您需要在控制器中有 public getter 来公开必要的值。不过,您可以保留节点和设置器之类的东西 private

如果你有多个类似于handleModalButton()的方法,并且对于所有这些方法,你都需要得到一组相似的值,那么你可以考虑创建一个接口,你的所有控制器class es可以实现。该接口将包括 getter 方法,您可以从中获取数据。然后showDialogModal()可以return接口类型,调用方法可以通过接口类型获取controller对象的引用。