-1

i developed a simple image editor in java, how can i do to show a message dialog when i click exit on a JFrame to ask the user if he want to save the work?

thank's everybody

iDoc
  • 35
  • 1
  • 5
  • possible duplicate of [Java making confirming exit](http://stackoverflow.com/questions/7695064/java-making-confirming-exit) – Frakcool Jun 16 '14 at 17:36

2 Answers2

0

Use a JOptionPane showing up on a specific event. For example the window closing event in the WindowListener.

WindowListener wl = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
          // add the option pane code here
     }
};
JFrame yourFrame = // your frame here
yourFrame.addWindowListener(wl);

A JOptionPane can be created as such:

final JOptionPane optionPane = new JOptionPane(
    "The only way to close this dialog is by\n"
    + "pressing one of the following buttons.\n"
    + "Do you understand?",
    JOptionPane.QUESTION_MESSAGE,
    JOptionPane.YES_NO_OPTION);

some option pane with yes and no buttons

Resulting option pane. Another alternative is to use one of the more specialized factory methods.

int option = JOptionPane.showConfirmDialog(null,"Exit Application?");
if(option == JOptionPane.YES_OPTION) {
    System.exit(0);
}

When you add a new close handler like this i would suggest to deactivate the default handler using this code:

yourFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

For more information about the setDefaultCloseOperation consult the documentation.

Hope this helps

Community
  • 1
  • 1
isaias-b
  • 2,255
  • 2
  • 25
  • 38
  • ok thank's but i don't understand how to: Use the setDefaultCloseOperation(...) on the frame to allow the WindowListener to take control of the closing event. – iDoc Jun 17 '14 at 10:05
0

Check out Closing an Application for basic information and examples.

You need to follow two basic steps:

  1. Add a WindowListener to the frame and handle the windowClosing(...) event
  2. Use the setDefaultCloseOperation(...) on the frame to allow the WindowListener to take control of the closing event.

The above link shows a simple example as well as a simple API that does both of the above steps so all you need to do is create an Action to handle your closing logic.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • @idoc, why did you unaccept this answer? I provided you with the exact steps required to provide a confirm dialog hours before isi did. In fact isi changed his answer after he saw my answer (because his answer was NOT complete. – camickr Jun 19 '14 at 14:30