event

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.

Ilias Tsagklis

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

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

0 Comments
Inline Feedbacks
View all comments
Back to top button