Before I show you an example of how to use a WindowListener, I like to mention couple important things.
1. Only the JFrame and JDialog classes can be used for registering WindowListener, but not the JPanel class.
2. Most of the time you would want to use the WindowAdaper class to register as a listener. Since the WindowListener interface declares seven methods, so if your class implements the WindowListener interface it must implement those seven methods which most of the time you are not interested all those events. Therefore, the Java class library provides the WindowAdapter class that implements the WindowListener interface, but its implemntation for those seven methods are empty. Therefore, you would need to override the methods that you're intertested by providing your own implementations.
---------------------------
Here is an example of how to intercept an WindowEvent to save data before exiting application when users click on the close button:
class MYFrame extends JFrame
{
public MYFrame()
{
super();
setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent evt )
{
saveData();
dispose();
exitJVM( 0 );
}
});
}
private void saveData()
{
// save data to disk file etc..
}
private void exitJVM( exitCode )
{
System.exit( exitCode );
}
//......
}
Please checking the syntax, I might be making a mistake with the syntax while I typing it.
Hope this will help.
|