Search code examples
javaswingjframejoptionpanewindowlistener

Ask user if wants to quit via JOptionPane


I'm using this code to confirm the user whether wants to quit or not when he CLICKS THE RED CROSS CLOSE BUTTON OF JFrame (right upper corner)

 Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};

int Answer = JOptionPane.showOptionDialog(null, "What would you like to do? ","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
    null, options,options[1]);
    if(Answer == JOptionPane.YES_OPTION){

        System.exit(0); 
    }
    else if (Answer == JOptionPane.CANCEL_OPTION) {
        return;
    } 

but the problem is if the user clicks CANCEL_OPTION the Frame Closes at all, but i want the user to still open the Frame and not allow the Frame to close. Guide me If I'm doing the blunder or something else?


Solution

  • I have a Real blunder

       Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};
    
       int Answer = JOptionPane.showOptionDialog(null, "What would you like to do?","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
    null, options,options[1]);
    if(Answer == JOptionPane.YES_OPTION){
    
        System.exit(0); 
    }
    else if (Answer == JOptionPane.CANCEL_OPTION) {
        return;
    } 
    

    It was clear that I have two Options i.e YES_NO_OPTION and I was calling the CANCEL_OPTION that was a real blunder so, the else-if should be changed to:

    else if (Answer == JOptionPane.NO_OPTION) {
        this.setDefaultCloseOperation(myclassreference.DO_NOTHING_ON_CLOSE);
    } 
    

    after this; its bingo !!! I've done!