Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a handler for window closing in Java Swing

I'm trying to call a function to do cleanup when my window (created with Java Swing) is closed . In my initialization code I do this:

public class FormLogin extends JFrame{
    private void initComponents(){
        ...
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt){
                formLoginWindowClosed(evt);
            }
        });
        ...
    }
}

But the function "formLoginWindowClosed" is never called when I press the exit button. I've also tried creating the listener with java.awt.event.WindowAdapter as an argument, but it didn't work either. How should I create the listener for window closing? Thanks in advance.

like image 473
Joel Avatar asked Dec 05 '12 09:12

Joel


People also ask

Which is the method used for window closing event?

The windowClosing() method is found in WindowListener interface and WindowAdapter class. The WindowAdapter class implements WindowListener interfaces. It provides the default implementation of all the 7 methods of WindowListener interface.

How do you close a frame in a Swing?

You can easily close your JFrame by clicking on the X(cross) in the upper right corner of the JFrame. However JFrame. setDefaultCloseOperation(int) is a method provided by JFrame class, you can set the operation that will happen when the user clicks the X(cross).

What is an event handler in Swing?

What is Event Handling? Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs.

What does pack () do in Swing?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location).


1 Answers

With the frame set to exit on close, windowClosed will never be called, mostly because the system has already exited before the event can be raised.

Try using windowClosing instead.

Alternatively, you could use a shut down hook

  • JVM Shutdown Hook in Java
  • Design of the Shutdown Hooks API
  • Java Shutdown hook – Runtime.addShutdownHook()
like image 98
MadProgrammer Avatar answered Sep 21 '22 23:09

MadProgrammer