Search code examples
javaswingjframejoptionpanewindowlistener

Java: JFrame on exit actions closes anyway even if "No" is clicked


Do you know why my JFrame closes anbyway even if I click the "No" Button? This is my code:

jframe.addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            int confirm = JOptionPane.showOptionDialog(jframe,
                    "Sei sicuro di voler chiudere EconomatoUTL?",
                    "Attenzione!", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);

            if (confirm == JOptionPane.YES_OPTION) {

                Runtime runtime = Runtime.getRuntime();
                try {
                    runtime.exec("cmd /C basexserver.bat stop");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.exit(1);
            }
        }
    });

I've found it in several forums and they say it works... Where's the mistake?


Solution

  • Check if you have set a default close operation like,

    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    

    even if you haven't, your frame will just hide (as default close operation is HIDE_ON_CLOSE) on clicking "No" option.

    instead add this as default close operation.

    jframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    

    this will keep your frame in existing state, if a user chooses "No" option.