-3

I looking for create mechanism for messaging when exiting and changes has been made. I want it to display a messagebox asking the user : ( Are you sure you don't want to save the changes - yes / no)

Upon closing the form by clicking on the button named 'Exit' or when use close button, ''X". Don't know the syntax for it, can someone help me please?

nobody
  • 19,814
  • 17
  • 56
  • 77
EmlX
  • 1
  • 1

1 Answers1

1

Here's some basic code on how to do it:

public class ClosingFrame extends JFrame {
    public ClosingFrame() {
        super("Shutdown hook");
        setSize(400, 400);
        setLocationByPlatform(true);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* important */

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                int showConfirmDialog = JOptionPane.
                        showConfirmDialog(ClosingFrame.this, "Do you want to save?");
                if (showConfirmDialog == JOptionPane.YES_OPTION) {
                    System.out.println("saved");
                    System.exit(0);
                } else if (showConfirmDialog == JOptionPane.NO_OPTION) {
                    System.out.println("not saved");
                    System.exit(0);
                } else {
                    System.out.println("aborted");
                    // do nothing
                }
            }

        });

        setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new ClosingFrame());
    }

}
Steffen
  • 3,999
  • 1
  • 23
  • 30
  • @EmlX You're welcome. If it was what you were looking for, please be so kind and accept the answer. :) – Steffen Apr 25 '14 at 21:25
  • Yes, it's useful but still is not what exactly i look for. I use your answer, but this is only half from this what i need. – EmlX Apr 25 '14 at 23:28