I am seeing the following code in a Swing demo application:
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
Why would you use this code to close the application? What would happen without it, and/or are there other (shorter) options to do this?
Why would you use this code to close the application?
As TimH said, you can log information, write out properties, or do any other clean up you want to do before exiting your Swing application.
Here's how the window closing code is normally used.
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitProcedure();
}
};
frame.addWindowListener(wndCloser);
public void exitProcedure() {
frame.dispose();
System.exit(0);
}
Because exitProcedure is a separate method, you can execute it from a JMenuItem action listener, like "Exit".
What would happen without it, and/or are there other (shorter) options to do this?
A shorter option is
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If you don't specify any default close operation, your Swing application continues to run after you close the JFrame. You wind up with dozens of running applications, doing nothing.