Search code examples
javaswingjoptionpanewindowlistener

How do I prevent a window from closing?


first sorry for my bad english.

Hi, i'm trying to use a confirmDialog with a YES_NO_OPTION. what i want is that when i close a frame a confimDialog will be displayed asking me if want to close.

if i press yes everyThing most be closed, if i press no the confirmDialog will disapear

but the problem is even if i press no button the frame close this is my code:

final JFrame frame = new JFrame("2D Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1600,600);
frame.setResizable(false);

    private void continuerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_continuerButtonActionPerformed
        int level=getlevel();
        System.out.println(niveau);
        if(niveau == 1)
        {
            this.dispose();
            frame.add(new Board());
            frame.setVisible(true);
            frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) 
            {
                doExitOption();
            }
            });
        }
    }

and this is doExitOption methode:

 public void doExitOption()
    {
        int option=JOptionPane.showConfirmDialog(null, "do you want to quit the game",    "Warnning",JOptionPane.YES_NO_OPTION);
            if(option == JOptionPane.YES_OPTION)
            {
                frame.dispose();
            }
    }

Solution

  • See Closing an Application. It can manager the default close operation for you.