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

Get Multiple Results from Custom Dialog -- JavaFX

我的 JavaFX 代码有点问题。我相信你们都知道可以使用 Optional< String >.showAndWait()TextInputDialog 获取输入。但是,当我有一个包含多个 TextFields 和一个 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);
    }
}

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

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

希望有人能提供帮助。

首先,为了获得不同类型的不同值(通用解决方案),只需定义一个新的数据结构,比如 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());
});

现在,无论您需要在何处使用对话框,您都可以:

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