palyxk palyxk - 23 days ago 13
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

You need to do three things:

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

frame.setDefaultCloseOperation(WindowConstants.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.
        super.windowClosing(e);
    }
});
  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) {
        System.exit(0);
    }
}
Comments