import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;

public class BeepTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        final Button button = new Button("Open Dialog #2");
        button.setOnAction(e -> showDialog(primaryStage));

        final Scene scene = new Scene(new StackPane(button), 600, 400);
        primaryStage.setTitle("Main Stage #1");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void showDialog(final Window owner) {
        final Dialog<ButtonType> dialog = new Alert(AlertType.INFORMATION);
        dialog.setTitle("Dialog #2");
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.initOwner(owner);
        dialog.setContentText("Press OK to open dialog #3");

        final Node defaultButton = dialog.getDialogPane().lookupButton(ButtonType.OK);
        // Use event filter instead of setOnAction, to be able to keep
        // dialog #2 open when hiding dialog #3 on Cancel.
        defaultButton.addEventFilter(ActionEvent.ACTION, event -> {
                if (!showOtherDialog(owner)) {
                    event.consume();
                }
            });
        dialog.show();
    }

    private boolean showOtherDialog(final Window owner) {
        final Dialog<ButtonType> secondDialog = new Alert(AlertType.CONFIRMATION);
        secondDialog.setTitle("Dialog #3");
        secondDialog.initModality(Modality.APPLICATION_MODAL);
        secondDialog.initOwner(owner);
        secondDialog.setContentText("Press OK to close dialogs #3 and #2.\n" +
                "Press Cancel to close only dialog #3");
        return secondDialog.showAndWait()
                .filter(type -> type == ButtonType.OK)
                .isPresent();
    }
}