How to make sure that when you try to close the application (in any way), a dialog appears confirming "Do you really want to close this application?" and only if the user clicks "Yes", close our application?

  • An incorrect question, many people pull the cord out of the socket or shoot a shotgun into the monitor :-) - psyhitus
  • Having shot the application in the monitor is not cut down) We'll have to finish it with kicks on the system unit. - uramer239

2 answers 2

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { if (...) { // пользователь подтвердил System.exit(0); } } }); 

Will work when trying to close in any way.

  • I understand that by closing the application in any way did not mean only closing the window .. or was I wrong? I immediately thought about the shutdown hook, but it is not suitable for graphics .. - cy6erGn0m
  • Well, this event will come when you close the application correctly. And correct closing will always lead to an attempt to close the main window (that is, which is JOptionPane.setRootFrame (frame)). Those. For example, when you try to turn off the computer when your application is open, a dialog will appear, but if you delete the process in the task-mahaner or pull the cord, then no. - Nicolas Chabanovsky
  • Well, there are more signals .. Speaking of the completion of the system: do not win this way, because the user does not have time to answer: the Windows will finish faster (if it is not win7) and just nailed the application. And the cancellation is not done .. - cy6erGn0m

As far as I know, it cannot be done so that "in any way." The only thing that can be done is in all places where it is possible to exit the application to make this request (of course, using some method to reuse the code).