event
Window closing event handling
In this example we are going to see how to handle window closing events. This is a very basic event handling when you are working on a UI Application.
Basically all you have to do to handle window closing events is:
- Create a simple
JFramewindow - Use
addWindowListenerto add a window listener to theJFrame - Override
windowClosingmethod ofWindowAdapterto handle a window closing event
Let’s see the code:
package com.javacodegeeks.snippets.desktop;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Main extends JFrame {
private static void showUI() {
Main jFrame = new Main();
jFrame.setSize(new Dimension(300, 250));
jFrame.add(new Button("Hello World"));
jFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jFrame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
showUI();
}
});
}
}
This is an example on how to handle Window Closing Events in Java.

