Home » Desktop Java » awt » event » Window closing event handling

About Ilias Tsagklis

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

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

@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.

(+1 rating, 1 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

 

Leave a Reply

avatar
  Subscribe  
Notify of