awt
Exit application when Frame is closed example
With this tutorial we shall show you how to exit from your application when a frame is closed. This is a very common use for most GUI applications.
This is very easy to do, all you have to do is:
- Create a new
WindowAdapterinstance. - Override
windowClosingmethod to customize the handling of that specific event. Now every time a window closes, this method will fire up. - Call System.exit(0) inside
windowClosingmethod to exit the application when the window closes.
Let’s see the code snippet that follows:
package com.javacodegeeks.snippets.desktop;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameCloseEventListener {
public static void main(String[] args) {
// Create the frame
Frame frame = new Frame();
// Add a listener for the close event
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
// Exit the application
System.exit(0);
}
});
// Display the frame
int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
}
}
This was an example on how to exit application when Frame is closed.
