import javax.swing.*;
import java.awt.event.*;public class WindowCloseTest extends JFrame{ public WindowCloseTest(){

setBounds(100,100,200,200);
setVisible(true);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//here!!!
addWindowListener(new MyWindowListener(this)); 
}
public static void main(String[] args){
WindowCloseTest test=new WindowCloseTest();

}

class MyWindowListener extends WindowAdapter{
JFrame frame;
public MyWindowListener(JFrame frame){
this.frame=frame;
}
public void windowClosing(WindowEvent e){
int sele=JOptionPane.showConfirmDialog(frame,"Save current work and exit?","Confirm Dialog",JOptionPane.YES_NO_CANCEL_OPTION);
switch(sele){
case JOptionPane.YES_OPTION:
    //save your work here
    setVisible(false);
    System.exit(0);
break;
case JOptionPane.NO_OPTION:
    setVisible(false);
    System.exit(0);
break;
case JOptionPane.CANCEL_OPTION:
    //do nothing
break;
}
}
}
}

解决方案 »

  1.   

    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    ......
    public void windowClosing(WindowEvent e){
       if(USER_CONFIRM_TO_EXIT){
          dispose();
       }
    }
      

  2.   

    在JFrame里有一个setDefaultCloseOperation(int);
    用以表明当用户alt+f4或者单击X时,在触发windowClosing后的操作;
    参数可以是
    HIDE_ON_CLOSE; 默认,自动隐藏,相当于hide();
    DISPOSE_ON_CLOSE; 相当于dispose();
    EXIT_ON_CLOSE;相当于System.exit(0);
    DO_NOTHING_ON_CLOSE;用于在需要用户选择的时候
      

  3.   

    this.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
         int selection = JOption.NO_OPTION;
         if( doc_modified )
            selection = JOption.showConfirmDialog(...);
         
         if(!doc_modified || selection == JOption.YES_OPTION) {
            System.exit(0);
         }
      }
      });
      

  4.   

    我把defaultCloseOperation设为do_nothing_on_close了,但仍然不行啊……
    这是我用的代码,大家帮看看有问题么?private boolean okToAbandon(){//用函数来判断
        if(!dirty){//检查是否修改过的标记
          return true;
        }
        int value = JOptionPane.showConfirmDialog(this,"Save current file?","Silent Editor",JOptionPane.YES_NO_CANCEL_OPTION);
        switch(value){
          case JOptionPane.YES_OPTION:
            return saveFile();//转保存对话框
          case JOptionPane.NO_OPTION:
            return true;
          case JOptionPane.CANCEL_OPTION:
          default:
            return false;
        }
      }然后
    void this_windowClosing(WindowEvent e) {
      if(okToAbandon()){
        System.exit(0);
      }
      else return;
    }
      

  5.   

    代码不够完整,可否[email protected]...
      

  6.   

    除去setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    用this.addWindowListener(new WindowAdapter() ...