2
votes

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,

2
Did you read the documentation? - James_D
I tried. I don't understand what it's saying. How does the result converter work? If I could see an example of actual code I think I could figure it out, but I've been looking around and haven't found anything about alerts besides displaying them and setting their type. - Jacob
There are three examples under "Option 1", "Option 2" and "Option 3". AIUI you don't use the result converter for an Alert. - James_D
The Dialog<R> documentation says "A result converter must always be set, whenever the type R is not Void or ButtonType.", but Alert extends Dialog<ButtonType> so the result converter doesn't apply. - James_D

2 Answers

3
votes

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...
    }
});
1
votes

İ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
    }
});