Java Swing How to - Call function on windows close








Question

We would like to know how to call function on windows close.

Answer

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/* w  w w.  ja v a 2 s .  c om*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

class WindowEventHandler extends WindowAdapter {
  public void windowClosing(WindowEvent evt) {
    System.out.println("Call your method here");
  }
}

public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame("Swing Frame");

    JLabel label = new JLabel("This is a Swing frame", JLabel.CENTER);

    frame.add(label);

    frame.addWindowListener(new WindowEventHandler());
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    frame.setSize(350, 200); // width=350, height=200
    frame.setVisible(true); // Display the frame
  }

}