How to programmatically close a JFrame
If you want the GUI to behave as if you clicked the X
close button then you need to dispatch a window closing event to the Window
. The ExitAction
from Closing An Application allows you to add this functionality to a menu item or any component that uses Action
s easily.
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
Not too tricky.
If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...)
will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.
If by Alt-F4 or X you mean hide the window, then frame.setVisible(false)
is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.
If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose()
is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).
dispose()
might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?
The Java Swing Tutorial on Window Listeners may help clarify things for you.