java - 如何监听JDialog的关闭事件?

标签 java swing desktop-application jdialog windowlistener

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

下面是我的 netbeans IED 中的代码。 我只是使用 WindowAdpter 来捕获关闭事件,请忽略由 ninebean 生成的虚拟代码。

谢谢。

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                   
 }

最佳答案

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

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

我个人建议不要直接从 JDialog 等顶级容器进行扩展,但这只是我的看法。

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

关于java - 如何监听JDialog的关闭事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18049514/

相关文章:

java - "RegionCacheAdapter Unable to clear cache. Failed on region null. Last key null null"

java - 如何将 JPanel 添加到 JFrame?

java - 如何关闭两个窗体但仅使用单个命令(SetVisible),Java

java - JXTable:对特定单元格而不是整个列使用 TableCellEditor 和 TableCellRenderer

java - java 桌面中的 session

javascript - 将文件从 Electron 发送到连接在 LAN 中的服务器

java - JSP 中的文档编辑器

java - 为 JVM 编译 C 代码或在 JVM 中嵌入 C 运行时

java - 类转换异常 - tabbedpane.getComponentAt(index)

winforms - NHibernate/CaSTLe.ActiveRecord ; session 管理;窗体