To close a window in Swing like JFrame or JDialog you have two options.
Call dispose()
Just call dispose() method:
public void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.
For instance:
frame.dispose();
dialog.dispose();
Dispatch a WINDOW_CLOSING
event
You can dispatch a new WindowEvent like this:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
If the window has attached a WindowListener it will be notified. If the frame's (or dialog's) default close operation is set then this action will be performed. The possible close operations are:
DO_NOTHING_ON_CLOSE
(defined inWindowConstants
): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.HIDE_ON_CLOSE
(defined inWindowConstants
): Automatically hide the frame after invoking any registered WindowListener objects.DISPOSE_ON_CLOSE
(defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.EXIT_ON_CLOSE
(defined inJFrame
and not available forJDialog
): Exit the application using the System exit method. Use this only in applications.