Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show prompt before closing JFrame [duplicate]

Tags:

java

swing

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);          
    }
  }
});
like image 251
user2125727 Avatar asked Mar 16 '13 12:03

user2125727


2 Answers

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);

like image 154
Hovercraft Full Of Eels Avatar answered Sep 27 '22 22:09

Hovercraft Full Of Eels


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);
        }
    }
});
like image 20
Nidhish Krishnan Avatar answered Sep 27 '22 22:09

Nidhish Krishnan