6

I am using windowClosing to confirm before closing a particular JFrame.

Before closing I get a confirm dialog but the problem is it closes even if I click the NO button. Any help please?

addWindowListener(new WindowAdapter() {

  @Override
  public void windowClosing(WindowEvent we)
  { 
    String ObjButtons[] = {"Yes","No"};
    int PromptResult = JOptionPane.showOptionDialog(null, 
        "Are you sure you want to exit?", "Online Examination System", 
        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, 
        ObjButtons,ObjButtons[1]);
    if(PromptResult==0)
    {
      System.exit(0);          
    }
  }
});
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user2125727
  • 173
  • 3
  • 4
  • 15
  • What is your JFrame's default close operation set to? Has it been set to: `jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);`? – Hovercraft Full Of Eels Mar 16 '13 at 12:05
  • 3
    `JOptionPane.showOptionDialog(null,"Are you sure you want to exit?","Online Examination System",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);`: Don't pass `null` for the first argument. Pass the parent frame of the dialog, otherwise your optionpane dialog may go behind your frame. – Guillaume Polet Mar 16 '13 at 12:09
  • Please mark an answer as "accepted". –  Feb 27 '18 at 16:52

4 Answers4

15

What is your JFrame's default close operation set to? You need to make sure that it been set to: jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
13

Try this

this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent we)
    { 
        String ObjButtons[] = {"Yes","No"};
        int PromptResult = JOptionPane.showOptionDialog(null,"Are you sure you want to exit?","Online Examination System",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
        if(PromptResult==JOptionPane.YES_OPTION)
        {
            System.exit(0);
        }
    }
});
Jonathandgorman
  • 102
  • 1
  • 10
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
2

You can set the default close option of your JFrame to DISPOSE_ON_CLOSE if it is set to EXIT_ON_CLOSE. In that case it will resolve your query something like:-

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

put this on on frame intialization

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Sachin
  • 3,424
  • 3
  • 21
  • 42