2

Hi i have a jFrame and I wish to ask the user whether he is sure to close the jframe when the close button is clicked:

    this.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
    Main ma = new Main();

    Object[] options = {"Yes", "NO"};

    int selectedOption = JOptionPane.showOptionDialog(ma, "Are you sure you want to close the system?", "Warning",
    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
    null, options, options[0]);

           if (selectedOption == JOptionPane.YES_OPTION) {
               System.exit(0);
           }

    else
    {
    }

    }
    }); 

How shall i undo the close operation when he selects the 'NO' button from the jpanel popup?

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3420231
  • 23
  • 1
  • 1
  • 5

2 Answers2

3

First you need to set the JFrame's default close action to do nothing on close:

myJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Then pressing the close button will not close the JFrame, and you will have to dispose of it in code.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

Set the default close operation to JFrame.DO_NOTHING, then use a WindowListener and listen for the windowClosing event. To close the frame now all you need to do is call dispose() on the frame. So:

public void windowClosing(WindowEvent e)  
{  
    JFrame frame = (JFrame)e.getWindow();  
    if (canClose(frame)) // you define canClose  
    {  
        frame.dispose();  
    }  
    else  
    {  
        // other stuff  
    }  
} 
Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66