In one of my programs, I want a dialog box to appear when a user tries to exit the application. Then the user must choose to save some state of the program, rather than saving or canceling the exit operation.
I wrote this, trying to find a solution first and then implement it:
import javax.swing.*; import java.awt.Dimension; import java.awt.event.*; class WL implements WindowListener { private boolean statussaved; private JFrame tframe; WL (JFrame frame) { statussaved = false; tframe = frame; } @Override public void windowActivated (WindowEvent w) { } @Override public void windowClosed (WindowEvent w) { } @Override public void windowDeactivated (WindowEvent w) { } @Override public void windowDeiconified (WindowEvent w) { } @Override public void windowIconified (WindowEvent w) { } @Override public void windowOpened (WindowEvent w) { } @Override public void windowClosing (WindowEvent w) { if (statussaved) { return; } final JDialog diag = new JDialog (tframe, "Save Progress", true); diag.setPreferredSize (new Dimension (500, 100)); diag.setResizable (false); diag.setDefaultCloseOperation (JDialog.DISPOSE_ON_CLOSE); JPanel notifypanel = new JPanel (); notifypanel.add (new JLabel ("Do you want to save the current status ?")); JButton yesbutton = new JButton ("Yes"); JButton nobutton = new JButton ("No"); JButton cancelbutton = new JButton ("Cancel"); yesbutton.addActionListener (new ActionListener () { @Override public void actionPerformed (ActionEvent a) {
It compiles and runs without any changes, so you can test it.
The Yes and No options work as expected, but I have absolutely no idea what to write the ActionListener
buttons in the ActionListener
. I want, when the user clicks the "Cancel" button, the dialog box disappears, but the main window remains visible (i.e. the program continues to work).
Now, since all this is implemented in the windowClosing
method, it is clear that some dispose JFrame
was sent to destroy the JFrame. This means that probably this cannot be done in the current project. I am not against reorganizing / redesigning all of this to make it work. It's just ... I don't know how.
Any ideas?
source share