Alert for unsaved changes before closing a Window

I’m using a Window to show an edit form, and the user can close the popup either by clicking the “x” in the top-right corner or with a keyboard shortcut (ESC).

I wonder if there is a way to intercept the click on the “x” (as well as the keyboard shortcut) so that I can display a warning to the user, like “Do you really want to quit without using the “save” button? There may be unsaved changes” before the window is closed. Looking at the Window API, it seems I can only use a Window.CloseListener, which unfortunately is notified after the window is closed (and there’s no .preventDefault() or alike in the CloseEvent API)

I could use a flag to tell if the closing event is “safe” or not, and messing inside the CloseListener, to show the window again while processing the event, and display the warning dialog, but I’m afraid this would interfere with how things are supposed to work, and may break in unpredictable ways (or at least cause glitches on the client side)

You need to extend the Window class and override close(). Here’s an example that overrides the close method and uses the ConfirmDialog add-on to ask the user if he wants to close the window or not.

  public class MyWindow extends Window {
      public void close() {
         ConfirmDialog.show(getUI(), "Please confirm",
               "Are you sure you want to close", "Yes", "No",
               new ConfirmDialog.Listener() {

                  @Override
                  public void onClose(ConfirmDialog dialog) {
                     if (dialog.isConfirmed()) {
                        MyWindow.this.close(true);
                     }
                  }
               });
      }

      public void close(boolean force) {
         if (force) {
            super.close();
         } else {
            close();
         }
      }
   }
}

Thanks! Overriding onClose works without any glitch :slight_smile: