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 JFrame window
  • Use addWindowListener to add a window listener to the JFrame
  • Override windowClosing method of WindowAdapter to 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() {


public void windowClosing(WindowEvent e) {





    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() {


public void run() {





This is an example on how to handle Window Closing Events in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button