How do I handle a window closing event in Swing?

Here you will see how to handle the window closing event of a JFrame. What you need to do is implement a java.awt.event.WindowListener interface and call the frame addWindowListener() method to add the listener to the frame instance. To handle the closing event implements the windowClosing() method of the interface.

But, instead of implemeting the java.awt.event.WindowListener interface which require us to implement the entire methods defined in the interface, we can create a an instance of WindowAdapter object and override only the method we need, which is the windowsClosing() method. Let’s see the code snippet below.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowClosingDemo extends JFrame {
    public static void main(String[] args) {
        WindowClosingDemo frame = new WindowClosingDemo();
        frame.setSize(new Dimension(250, 250));
        frame.add(new Button("Hello World"));

        // Add window listener by implementing WindowAdapter class to
        // the frame instance. To handle the close event we just need
        // to implement the windowClosing() method.
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {

        // Show the frame

How do I close a JFrame application?

Closing a JFrame application can be done by setting the default close operation of the frame. There are some defined constant for the default operation. These constants defined in the javax.swing.WindowConstants interface includes EXIT_ON_CLOSE, HIDE_ON_CLOSE, DO_NOTHING_ON_CLOSE and DISPOSE_ON_CLOSE.

To exit an application we can set it to EXIT_ON_CLOSE, this option will call the System.exit() method when user initiate a close operation on the frame.

package org.kodejava.example.swing;

import javax.swing.*;

public class MainFrameClose extends JFrame {
    public static void main(String[] args) {
        MainFrameClose frame = new MainFrameClose();
        frame.setSize(250, 250);

        // Be defining the default close operation of a JFrame to
        // EXIT_ON_CLOSE the application will be exited by calling
        // System.exit() when user initiate a close event on the
        // frame.