How to Close a JFrame in Java With a Button
JFrame is the standard window in the Java Swing component set. By default, it provides a title bar and a default "Close" button, a small "X" on the upper-right corner. However, you can also close the frame using a JButton, the Swing version of a simple button. The specific implementation you need depends on whether you want to simply hide the window or dispose of it, freeing up the resources it was using and potentially exiting the program.
Instructions
-
-
1
Create the button and add it to your frame. For example:
JButton closeButton = new JButton("Close");
theFrame.getContentPane().add(closeButton); -
2
Attach an action listener to the button. The easiest way to do it on the spot is to define a new listener right when you attach it. For example:
closeButton.addActionListener(new ActionListener () { void actionPerformed(ActionEvent e) {/* close action here */ } });
-
-
3
Define the close action in the method body of "actionPerformed." This is usually a call to hide or destroy the window. To hide the window, call:
theFrame.setVisible(false);
If you want to destroy the window, first hide it, then call:
theFrame.dispose();
-
4
Pack the frame and set the current frame to be visible. For example:
theFrame.pack();
theFrame.setVisible("true");
-
1
Tips & Warnings
If you call Frame.dispose() and there are no non-daemon threads running or other GUI components visible, the program will exit.
References
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images