2

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.

m4t5k4
  • 55
  • 9

1 Answers1

1

Why not just make the handler a standalone class (or a public static inner class in some other convenient class):

public class CloseWindowConfirmation implements 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();
        }
    }
}

Then you just do

public void addWindowEventHandlers() {
    view.getScene().getWindow().setOnCloseRequest(new CloseWindowConfirmation());
}
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Thanks @James_D ;) One more question, how can I extract a method if it has variables in it? Like: if (alert.getResult().equals(yes)) { view.getTextField(); view.getScene().getWindow().hide(); } – m4t5k4 Feb 28 '17 at 16:45
  • Just make the value you need a property in the handler class and pass it to the constructor. – James_D Feb 28 '17 at 16:53