awt

Exit application when Frame is closed example

With this tutorial we shall show you how to exit from your application when a frame is closed. This is a very common use for most GUI applications.

This is very easy to do, all you have to do is:

  • Create a new WindowAdapter instance.
  • Override windowClosing method to customize the handling of that specific event. Now every time a window closes, this method will fire up.
  • Call System.exit(0) inside windowClosing method to exit the application when the window closes.

 
 
Let’s see the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

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

public class FrameCloseEventListener {

  public static void main(String[] args) {

// Create the frame

Frame frame = new Frame();

// Add a listener for the close event

frame.addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent evt) {

  // Exit the application

  System.exit(0);

    }

});

// Display the frame

int frameWidth = 300;

int frameHeight = 300;

frame.setSize(frameWidth, frameHeight);

frame.setVisible(true);

  }

}

 
This was an example on how to exit application when Frame is closed.

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button