Home » Desktop Java » swing » JFrame » Create JFrame window with window close event

About Ilias Tsagklis

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

Create JFrame window with window close event

This is an example on how to create a JFrame window with window close event. Pairing a window with a closing event is a very common practice in most GUI applications. When the user closes a window, it usually means that you have to release several resources or event exit the application.

The basic steps to create a JFrame with a window closing event is:

  • Create a class that extends JFrame.
  • Create a class that extends WindowAdapter.
  • Override the windowClosing method. Now every time the window closes, this method will fire up.

Let’s take a look at the code snippets that follow:

package com.javacodegeeks.snippets.desktop;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class CreateJFrameWindowWithWindowCloseEvent  extends JFrame {

	private static final long serialVersionUID = 1L;

	public CreateJFrameWindowWithWindowCloseEvent() {
		setTitle("Simple Frame");

  setSize(200, 200);
		addWindowListener(new CustomWindowAdapter(this));
	}

	private static void createAndShowGUI() {

  //Create and set up the window.

  JFrame frame = new CreateJFrameWindowWithWindowCloseEvent();

  //Display the window.

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

public void run() {

    createAndShowGUI(); 

}

  });
    }

	class CustomWindowAdapter extends WindowAdapter {

		CreateJFrameWindowWithWindowCloseEvent window = null;

		CustomWindowAdapter(CreateJFrameWindowWithWindowCloseEvent window) {
			this.window = window;
		}

		// implement windowClosing method
		public void windowClosing(WindowEvent e) {
			// exit the application when window's close button is clicked
			System.exit(0);
		}
	}

}

 
This was an example on how to create a JFrame with a window closing event.

(No Ratings Yet)
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