javaswingjframewindowlistenerjpopup

Popup for JFrame close button


i am doing some basic Java Swing application (beginner level) . what i have to do is when i press close button on JFrame to colse the window i want a JOptionPane Confirm Dialog instead of straightforward close

here is the code JFrame

   JFrame  frame= new JFrame("frame"); 
   frame.setSize(300,300);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setVisible(true);
   frame.pack();

and JOptionPane code goes like this

   final JOptionPane optionPane = new JOptionPane("Are You sure?",JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);

so when Close button on JFrame pressed this popup should come up instead of Direct closing
Please guide me how i can do it .. Thanks in advance


Solution

  • You can do it by following steps:

    1. Replace the line frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); with frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    2. Implement WindowListener and override its all abstract methods. You can find it here.

    3. Override the public void windowClosing(WindowEvent e) method some this way:

       @Override
       public void windowClosing(WindowEvent e){
             int result = JOptionPane.showConfirmDialog(null, "Are you sure,"Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
      
             if(result == JOptionPane.YES_OPTION){
                     System.exit(0);
             }else{
                     //Do nothing
             }
       }