Confirm form closure

Asked

Viewed 801 times

2

I need to ask if I want to close the window that is open. I made the following form, but in any of the options, it closes. I currently use this event option:

private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
    if (JOptionPane.showConfirmDialog(null, "Você deseja realmente fechar essa janela? Todas mensagens serão perdidas") != JOptionPane.YES_NO_OPTION) 
    {
        this.setVisible(false);
    }
}

This is a second form, I have the main one, with the options and I have the second one, where I ask if you really want to close. It is a Jframe.

Another detail is that in the message displayed there are 3 options: YES, NO and CANCEL. I only want the two options YES and NO.

2 answers

3


whereas the segundo if it is a Jframe within the main Jframe, the right one would be:

JFrame segundo = new JFrame();
segundo.setBounds(100, 100, 450, 300);
// No método abaixo, diz que não é para fazer nada ao apertar receber o comando de fechar
segundo.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
segundo.setVisible(true);
//sobrescreve o evento que é acionado quando se tenta fechar o JFrame
segundo.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        super.windowClosing(e);
        //pergunta para o usuário qual é a decisão dele
        if (JOptionPane.showConfirmDialog(
                null, 
                "Você deseja realmente fechar essa janela? "
                        + "Todas mensagens serão perdidas",
                        "Fechar",
                        JOptionPane.YES_NO_OPTION
                ) == JOptionPane.YES_OPTION) {
            //caso deseja fechar, deixa torna invisível
            segundo.setVisible(false);
        }
        //não tem else pois o comportamento normal é DO_NOTHING_ON_CLOSE
    }
});
  • I entered the code, but when I click NO, it closes anyway. The event used (windowClosing) is correct?

  • Actually I use override another event, let me do a short example here because I didn’t compile the code I posted above.

  • All right, stand by. Just one detail: this is a second form, I have the main one, with the options and I have the second one, where I ask if you really want to close.

  • What object is this form? A Jframe?

  • Yeah, it’s a Jframe

  • 1

    Perfect. Thank you!

Show 1 more comment

0

The variable evt must have a property cancel or something like that. Just set yourself as true in case the user did not want to close that the closing will be canceled and you can hide the form.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.