palyxk palyxk -4 years ago 175
Java Question

JFrame closing on dialog

public static int clickOnExit() {
int dialogButton=JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog(null, sharedConstants.exitMessage,"Confirm",dialogButton);
if(dialogButton == JOptionPane.YES_OPTION){return JFrame.EXIT_ON_CLOSE;}
else{return JFrame.DO_NOTHING_ON_CLOSE;}


for confirm(YES) it works, but i am not sure if cancel option is solved properly. i just want to cancel JOptionPane and keep frame opened.

Answer Source

You need to do three things:

  1. Set your main application frame to do nothing on close.


  1. Register a WindowListener that listens to the windowClosing event.
frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        maybeExit(); // Will not return if user clicks yes.
  1. Write code to conditionally call System.exit if the user confirms they wish to exit the application.
private void maybeExit() {
    int yesNo = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

    if (yesNo == JOptionPane.YES_OPTION) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download