Java: How to cancel application exit

强颜欢笑 提交于 2019-12-01 17:36:59
Mersenne

Replace

mainframe.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

with

mainframe.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);

If user cancels closing - do nothing. If agrees - call dispose() manually.

Have a look at JOptionPane, which handles most of this stuff for you, e.g.

JOptionPane.showConfirmDialog(frame, "please choose one", 
      "information",      
      OptionPane.YES_NO_CANCEL_OPTION, 
      JOptionPane.INFORMATION_MESSAGE);

Your DefaultCloseOperation needs to be DO_NOTHING_ON_CLOSE so that your dialog can handle things - otherwise the window will get disposed before the user can cancel it. Then you manually close the window or exit the application or whatever according to the user's choice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!