SagittariusA
SagittariusA

Reputation: 5427

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?

Upvotes: 2

Views: 264

Answers (2)

Shailesh Aswal
Shailesh Aswal

Reputation: 6802

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.

Upvotes: 3

Dormouse
Dormouse

Reputation: 1637

You are already in a windowClosing event, which isn't cancelled. So the window will be closed.

It's been a while, but you can probably cancel the event using the windowEvent.

Upvotes: 1

Related Questions