0

I'm trying that when a user tries to close a window in the normal way (clicking on the X) a popup shows up saying "Are you sure you want to close this window?" and then if he chooses "No", I want the window not to close, which is closing wether he chooses Yes or No.

My current code for this listener is:

frmContactarEspecialista.addWindowListener(new FrameWindowListener());    

private class FrameWindowListener extends WindowAdapter {
        @Override
        public void windowClosing(WindowEvent arg0) {
            int salir = JOptionPane.showOptionDialog(frmContactarEspecialista, "Si cierra esta ventana se descartará el email, ¿continuar?", "Salir",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);

            if (salir != 0){

            }
        }
    }

After marking my post as duplicate, I alredy tried that with:

private class FrameWindowListener extends WindowAdapter {
        @Override
        public void windowClosing(WindowEvent arg0) {
            int salir = JOptionPane.showConfirmDialog(frmContactarEspecialista, "Si cierra esta ventana se descartará el email, ¿continuar?", "Salir",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (salir == JOptionPane.NO_OPTION) {
                System.out.println("do nothing");
            }
        }
    }

And it prints "do nothing" but still closes the window.

what should I change or put into the if so it doesn't close the window?

Thanks

Ulises CT
  • 1,361
  • 1
  • 12
  • 21

1 Answers1

0

I found the answer! First you have to add something to your frame.

nameofyourframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

So, when you press X, the window won't close at all. Now let's go to your listener.

if(salir != 0){
    nameofyourframe.dispose();
}

So, if the answer is yes, it will close your program and window, if no nothing will happen!

Joza100
  • 338
  • 4
  • 16