日期:2014-05-20  浏览次数:20726 次

在frame关闭的时候添加对话框,按取消不让它关闭
主程序代码如下:
        public   static   void   main(String   args[]){
PlafFrame   frame=new   PlafFrame();
                frame.setVisible(true);
                frame.addWindowListener(new
                WindowAdapter(){
                            public   void   windowClosing(WindowEvent   e){
                                  exitDialog();
                            }
                    });
        }
        static   void   exitDialog(){
int   option=0;
                option=JOptionPane.showConfirmDialog(null, "确定要退出吗? ", "关闭 ",JOptionPane.YES_NO_OPTION);
                if(option==JOptionPane.YES_OPTION){
                        System.out.println( "已经退出 ");
                        System.exit(0);
                }
                if(option==JOptionPane.NO_OPTION){
                        System.out.println( "没有退出 ");
                        frame.setVisible(true);       //我发现这样子不行,不知道怎样才可以
                }
        }
}

------解决方案--------------------
我是这么写的 不过好像有点不太好 强制退出

import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class close extends JFrame {

private static final long serialVersionUID = 1L;

private JPanel jContentPane = null;

/**
* This is the default constructor
*/
public close() {
super();
initialize();
}

/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle( "JFrame ");
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
int i=javax.swing.JOptionPane.showConfirmDialog(null, "要退出吗? ", "退出 ", javax.swing.JOptionPane.YES_NO_OPTION);
if (i==javax.swing.JOptionPane.YES_OPTION)
{
System.exit(1);
}
}
});

this.setVisible(true);
}

public static void main(String[] args)
{
new close();
}

/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());