JavaFX create alert and get result

主宰稳场 提交于 2020-03-16 07:42:32

问题


For my CS class they require us to use JavaFX alerts. I can make an alert appear, but how do I get what button was clicked? What would be the best way to go about getting this data?

Also if possible, I'd like to make it have a drop down panel and when the user selects and option the alert closes and prints what the user selected.

Here's some example code that I have. When I click one of the buttons, it just closes the dialog.

Alert a = new Alert(AlertType.NONE, "Promote pawn to:", new ButtonType("Queen"), new ButtonType("Rook"));
a.setTitle("Title");
a.setHeaderText("My header text");
a.setResizable(true);
a.setContentText("Content text");
a.showAndWait();

Thanks,


回答1:


You can do

ButtonType queen = new ButtonType("Queen");
ButtonType rook = new ButtonType("Rook");
Alert a = new Alert(AlertType.NONE, "Promote pawn to:", queen, rook);
a.setTitle("Title");
a.setHeaderText("My header text");
a.setResizable(true);
a.setContentText("Content text");
a.showAndWait().ifPresent(response -> {
    if (response == queen) {
        // promote to queen...
    } else if (response == rook) {
        // promote to rook...
    }
});



回答2:


İf you want to do it with Non-Blocking type of code:

final Alert alert2 = new Alert(Alert.AlertType.CONFIRMATION);
alert2.show();
alert2.setOnCloseRequest(new EventHandler<DialogEvent>() {
    @Override
    public void handle(DialogEvent event) {
        ButtonType result=alert2.getResult();
        String resultText=result.getText();
        //result logic
    }
});


来源:https://stackoverflow.com/questions/33839272/javafx-create-alert-and-get-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!