In two different classes I have the same code as below. This section of code enables me to add an alert screen when the user closes a window. What is the best way to avoid writing the same thing twice?
public void addWindowEventHandlers() {
view.getScene().getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setHeaderText("You are about to exit the game.");
alert.setContentText("Are you sure?");
alert.setTitle("Warning");
alert.getButtonTypes().clear();
ButtonType no = new ButtonType("No");
ButtonType yes = new ButtonType("Yes");
alert.getButtonTypes().addAll(no, yes);
alert.showAndWait();
if (alert.getResult() == null || alert.getResult().equals(no)) {
event.consume();
}
}
});
}
Little note: for this project I have to work with model view presenter.