如何监控JDialog的close事件?

时间:2013-08-05 01:43:21

标签: java swing desktop-application jdialog windowlistener

我有一个棘手的问题。当有人点击窗口右上角的关闭标志时,我需要弹出一个确认消息框,供用户决定是否关闭。但它不起作用。无论您在弹出消息框中选择什么,对话框都将始终关闭。但是当我创建JFrame时,相同的逻辑工作正常。

以下是我的netbeans IED中的代码。 我只是使用WindowAdpter捕获close事件,plz igore由neatbean生成的虚拟代码。

感谢。

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class TestClosingDialog extends javax.swing.JDialog {

    public TestClosingDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();


        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                int a = JOptionPane.showConfirmDialog(null,"Are you sure you need to close?", "Tip", JOptionPane.YES_NO_OPTION);
                if (a == 0) {  
                    System.out.println("yes " + a);
                    System.exit(0);  //close 
                } else if (a==1) {
                    System.out.println("no " + a);
                } 
            }
       });
    }

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            TestClosingDialog dialog = new TestClosingDialog(new JFrame(), true);
            dialog.setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
// End of variables declaration                   
 }

1 个答案:

答案 0 :(得分:1)

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);更改为setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING);

这将要求您手动dispose对话框。根据您的需要,您只需将System.exit(0);更改为dispose();

即可

我个人建议不要直接从像JDialog这样的顶级容器扩展,但那只是我。

我更喜欢使用像JPanel这样的东西,它有一个可以显示对话框的辅助方法。此方法将创建对话框并向其添加面板,例如