从自定义对话框获取多个结果 -- JavaFX

xke*_*vio 4 java dialog javafx input option-type

我的 JavaFX 代码有一个小问题。我相信你们都知道可以TextInputDialog使用Optional< String >and来从 a 获取输入.showAndWait()TextFields但是,当我有一个包含 multiple和 a 的自定义对话框时,我该怎么办ChoiceBox?单击“确定”后如何获得所有结果?我想过,List<String>但没能做到。代码(自定义对话框):

public class ImageEffectInputDialog extends Dialog {

    private ButtonType apply = new ButtonType("Apply", ButtonBar.ButtonData.OK_DONE);
    private ButtonType cancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);

    public ImageEffectInputDialog(String title) {
        setTitle(title);
        setHeaderText(null);

        GridPane dPane = new GridPane();
        Label offsetX = new Label("Offset X: ");
        Label offsetY = new Label("Offset Y: ");
        Label color = new Label("Shadow Color: ");
        TextField offsetXText = new TextField();
        TextField offsetYText = new TextField();
        ChoiceBox<String> shadowColors = new ChoiceBox<>();
        shadowColors.getItems().add(0, "Black");
        shadowColors.getItems().add(1, "White");
        dPane.setHgap(7D);
        dPane.setVgap(8D);

        GridPane.setConstraints(offsetX, 0, 0);
        GridPane.setConstraints(offsetY, 0, 1);
        GridPane.setConstraints(offsetXText, 1, 0);
        GridPane.setConstraints(offsetYText, 1, 1);
        GridPane.setConstraints(color, 0, 2);
        GridPane.setConstraints(shadowColors, 1, 2);

        dPane.getChildren().addAll(offsetX, offsetY, color, offsetXText, offsetYText, shadowColors);
        getDialogPane().getButtonTypes().addAll(apply, cancel);
        getDialogPane().setContent(dPane);
    }
}
Run Code Online (Sandbox Code Playgroud)

代码(我想要结果的地方)

if(scrollPane.getContent() != null && scrollPane.getContent() instanceof ImageView) {
    // ImageEffectUtil.addDropShadow((ImageView) scrollPane.getContent());
    ImageEffectInputDialog drop = new ImageEffectInputDialog("Drop Shadow"); 
    //Want the Results here..
}
Run Code Online (Sandbox Code Playgroud)

我希望有人能够提供帮助。

Alm*_*asB 5

首先,为了获得不同类型的不同值(通用解决方案),只需定义一个新的数据结构,例如Result,其中包含 offsetX、offsetY 等字段以及您需要的任何其他字段。接下来,扩展Dialog<Result>而不只是Dialog. 最后,在您的构造函数中,ImageEffectInputDialog您需要设置结果转换器,如下所示:

setResultConverter(button -> {
    // here you can also check what button was pressed
    // and return things accordingly
    return new Result(offsetXText.getText(), offsetYText.getText());
});
Run Code Online (Sandbox Code Playgroud)

现在,无论您在哪里需要使用该对话框,都可以执行以下操作:

    ImageEffectInputDialog dialog = new ImageEffectInputDialog("Title");
    dialog.showAndWait().ifPresent(result -> {
        // do something with result object, which is of type Result
    });
Run Code Online (Sandbox Code Playgroud)