Tuesday, September 01, 2009

Griffon Tip: Intercepting Window Closing Events

When building an editor of sorts, it is often useful to intercept the window closing event so that you can prompt the user to save if the editor has unsaved changes.  To do this in Griffon, we first need to change the defaultCloseOperation and define a windowClosing event handler on our application node in the view:

application(title:'Editor', size:[800,600], locationByPlatform: true,
    defaultCloseOperation: WindowConstants.DO_NOTHING_ON_CLOSE, 
    windowClosing: { evt -> 
        // check if the editor needs saving
    }) {
// the rest of your view code here

If we run our application now, we should notice that...the windowClosing event handler never runs.  Turns out that there's one more step--we need to tell Griffon that we want to explicitly handle shutting down the application.  We do this by setting autoShutdown=false in griffon-app/conf/Application.groovy Once this is set, we should notice that our windowClosing event handler runs.  Since Griffon is no longer responsible for automatically shutting down our application, we must make sure to call app.shutdown() somewhere in our closing logic or the user won't be able to exit the app.

No comments: