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

时间:2018-06-05 22:30:14

标签: java javafx modal-dialog fxml

我有一个模态类:

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方法?这个模态可以被赋予不同的FXML文件,因此它返回的数据可能不同。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以让DialogModal.showDialogModal()返回生成的模态对话框窗口的控制器。

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()中控制器的类,否则您将获得ClassCastException。当然,您需要在控制器中使用public个getter来公开必要的值。您可以保留节点和设置器private等内容。

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

相关问题