Xoetrope
View

Catching Close Events

When a Java application shuts down the JVM normally exits, but a user friendly application will need to prompt the user to save settings and data. So how is this accomplished in XUI?

Trapping the Window Close event is usually accomplished with the WindowListener interface and you can use this interface directly, by calling project.getAppFrame().addWindowListener(...) for one of your pages.

However this doesn't help much if you want an exit or shutdown button or menu item within your application. Furthermore if you want to shut your application down via some other route you may not even get a Window Closing event as the JVM may just exit. Fortunately the JVM provides a shutdown hook that is called just prior to exit and this hook can be used to do any last minute cleanup.

XUI wraps the shutdown hook with the XLifeCycleListener interface. The interface includes a canClose method that allows you to prompt the user to save data etc prior to close and allows you to veto the shutdown if UI is being used to close the application. To add the listener a startup.properties entry is required:

LifeCycleListener=xui.projects.test.catchexit.ApplicationManager

If all you want to do is catch the exit event then the listener is easy to implement:


package xui.projects.test.catchexit;

import javax.swing.JOptionPane;
import net.xoetrope.xui.XLifeCycleListener;
import net.xoetrope.xui.XProject;

public class ApplicationManager implements XLifeCycleListener
{    
    /** Creates a new instance of ApplicationManager */
    public ApplicationManager() 
    {
    }

    public void initialize( XProject xProject ) 
    {
    }

    public void shutdown() 
    {
    }

    public boolean canClose( XProject xProject ) 
    {
        int rc = JOptionPane.showConfirmDialog( null, 
           "Do you really want to exit now?", 
           "Closing the application", 
           JOptionPane.YES_NO_OPTION, 
           JOptionPane.QUESTION_MESSAGE );
        return ( rc == JOptionPane.YES_OPTION );
    }
    
}

Once the lifecycle listener has been added a popup message appears when the user tries to close the application and if the user answers 'no' the application continues as before. If some other UI mechanism (an exit menu item or an exit button) is being used its action can be handled with a call to the shutdown method. The shutdown method calls through to the lifecycle listener, so you get a common shutdown mechanism.


    public void doExit()
    {
        XApplicationContext appContext = project.getApplicationContext();
        appContext.shutdown();
    }

Enhacements

The shutdown procedure can be further enhanced to prevent the JVM from exiting upon shutdown, and this is sometimes useful if some other activity is to continue after the applications user interface is dismissed. In the MetroBank example this technique is employed so that the application can be restarted from a SystemTray item.

Resources

See the