Preventing JFrame window from closing
- Details
- Written by Nam Ha Minh
- Last Updated on 06 July 2019   |   Print Email
This quick tutorial shows you how to write simple Java code in order to handle the situation in which the user clicks close button to quit your Swing program while he or she hasn’t saved the work yet. The program asks the user to save changes (if any) before quitting your program. That’s standard behavior in a typical desktop application.
First, you need to set default close operation on a JFrame to “do nothing”:
jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
That prevents the default behavior which the frame will be closed if the user clicks on the close button. This statement is very important to handle the application closing situation we are discussing.
Second, add a WindowListener for the frame. The listener will listen to the windowClosing() event which is triggered immediately when the user clicks the close button, before the window is disposed. For example:
jFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { handleClosing(); } });
Here, we create an anonymous class that extends the WindowAdapter class for brevity: implement only the windowClosing() method instead of all methods defined by the WindowListener interface.
And typically, the handleClosing() method checks whether the user saved changes or not. If not, display a warning message dialog that notifies the user, shows options (Yes, No, Cancel) and waits for the user’s answer. Otherwise, dispose the window and exit the application as normal. Here’s how the message dialog looks like:
If the user chooses Yes, save changes and quit the program; If No is chosen, quit the program anyway; and if Cancel is clicked, do nothing and return back to the program.
Here’s full source code of the demo program, for your reference:
package net.codejava.swing; import java.awt.HeadlessException; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.Icon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; /** * This simple Swing program demonstrates how to handle window closing * event in order to prevent the window from closing if the user has * not saved changes. * @author www.codejava.net * */ public class JFrameClosingDemo extends JFrame { public JFrameClosingDemo() throws HeadlessException { super("JFrame Handle Closing Demo"); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { handleClosing(); } }); setSize(480, 320); setLocationRelativeTo(null); } private void handleClosing() { if (hasUnsaveData()) { int answer = showWarningMessage(); switch (answer) { case JOptionPane.YES_OPTION: System.out.println("Save and Quit"); dispose(); break; case JOptionPane.NO_OPTION: System.out.println("Don't Save and Quit"); dispose(); break; case JOptionPane.CANCEL_OPTION: System.out.println("Don't Quit"); break; } } else { dispose(); } } private int showWarningMessage() { String[] buttonLabels = new String[] {"Yes", "No", "Cancel"}; String defaultOption = buttonLabels[0]; Icon icon = null; return JOptionPane.showOptionDialog(this, "There's still something unsaved.\n" + "Do you want to save before exiting?", "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, icon, buttonLabels, defaultOption); } private boolean hasUnsaveData() { // checks if there's still something unsaved // this method always return true for demo purpose return true; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new JFrameClosingDemo().setVisible(true); } }); } }
Run this program and click on the window’s close button, a warning message dialog appears:
And try to click the Yes, No or Cancel button, the program behaves as mentioned earlier.
For your convenience, you can download source code and executable jar file of this demo program under the Attachments section.
API References:
Other Java Swing Tutorials:
- Java Swing Hello World Tutorial for Beginners Using Text Editor
- JFrame basic tutorial and examples
- JPanel basic tutorial and examples
- JLabel basic tutorial and examples
- JTextField basic tutorial and examples
- JButton basic tutorial and examples
- JComboBox basic tutorial and examples
- JCheckBox basic tutorial and examples
- JList basic tutorial and examples
Comments