Netbeans RCP: Asking before exiting the application

This article explains how to present a confirmation dialog asking if the user really wants to close the application.

This article was originally published on techtavern.wordpress.com.

The following solution registers a callable via @OnStop annotation. The callable is an opportunity to cancel closing the application by returning false.

import java.util.concurrent.Callable;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.modules.OnStop;

@OnStop
public class ApplicationOnStop implements Callable<Boolean> {
@Override
   public Boolean call() throws Exception {
      NotifyDescriptor d = new NotifyDescriptor.Confirmation("Close application?", NotifyDescriptor.YES_NO_OPTION)
      return DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.YES_OPTION; 
   } 
}