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.
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.
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 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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With