java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to handle a window closing event?

Here you'll see how you can handle the window closing event of a JFrame. What you need to do is add a WindowListener to the frame instance and implement the windowClosing() method.

package com.javacoderanch.example.swing;

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

import javax.swing.JFrame;

public class WindowClosingExample extends JFrame {
    public static void main(String[] args) {
	WindowClosingExample frame = new WindowClosingExample();
	frame.setSize(new Dimension(200, 200));
	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