Search code examples
javaswingjoptionpane

Option pane stopping the program independently of the choice


So, I have a JOptionPane and when I click the "red X" of JFrame the confirmation dialog pops out. The problem is that, whatever I choose it stops the programs. How I can NOT stop the program when I click "NO" ?

Also, If I have two frames opened, how I can create it to close just the selected one ? Because it is closing both of the frames.

if (JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing",
        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
    System.exit(0);
}

Solution

  • First you need to set

    frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    

    then you need to add a WindowListener to your frame like this:

     frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent ev) {
    if (JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                    System.exit(0);
                }
    
    }});
    

    And if you have 2 frames but you need to close just one u can use frame.dispose(); instead of System.exit(0);