Popup for JFrame close button

前端 未结 2 641
旧巷少年郎
旧巷少年郎 2021-02-10 22:42

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

2条回答
  •  悲哀的现实
    2021-02-10 23:07

    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
             }
       }
      

提交回复
热议问题