How to make a decision structure to close a window?

2

In the code below, I want you to choose% while the window closes, and when choosing sim the window remains open.

private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
    // TODO add your handling code here:

    int Confirm = JOptionPane.showConfirmDialog(null,"Encerrar?","sim ou nao", JOptionPane.YES_NO_OPTION);
    if (Confirm == JOptionPane.YES_OPTION) {
        JOptionPane.showMessageDialog(null, "");
        System.exit(0);
    } else if (Confirm == JOptionPane.NO_OPTION){
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    }
}

It does not give any error, the problem is that choosing não the window closes. Until then correct, but choosing sim it closes the same way.

    
asked by anonymous 29.05.2014 / 20:46

2 answers

1

You have to use YES_NO_OPTION, try the code snippet below, which I took from an old project of mine. Any doubt is just to return. Hugs

frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            if (JOptionPane.showConfirmDialog(frame, 
                "Titulo", "Tem certeza ?", 
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
                System.exit(0);
            }
        }
    });
    
30.05.2014 / 01:46
0

I create a private method (Private void), ConfirmSaid, and then only invoke it every time I need to use the formWindowClosing or KeyPressed Events sometimes, so your system saves code and gets smaller and easier to understand =).

private void ConfirmarSaida(){

        JOptionPane sair = new JOptionPane();
        int Sair = sair.showConfirmDialog(null,"Você deseja sair do programa?","Sair",JOptionPane.YES_NO_OPTION);
      if(Sair == JOptionPane.YES_OPTION){
       //    System.exit(0);
       this.dispose();

      }else{
         if(Sair == JOptionPane.NO_OPTION){

         }
      }


}

Ah! and do not forget to configure the JFrame or JInternalFrame, or change the SetDefaultCloseOperation to DO_NOTHING, so when you click on the X of the window it will only use your JOptionPane if you leave DISPOSE or EXIT_ON_CLOSE on SetDefaultCloseOperation, it will close even if you click not on JOptionPane on the conditional exit.

I hope to help with something.

    
04.03.2016 / 22:57