java - 为什么用ConfirmDialog关闭Frme窗口会在两种情况下(确定和取消)关闭?

标签 java swing jframe windowlistener

这是我的代码:

            addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
               int a = JOptionPane.showConfirmDialog(null, 
                            "Are you sure you want to exit the program?", "Exit Program ",
                            JOptionPane.YES_NO_OPTION);
               System.out.println(a);
               if(a==JOptionPane.OK_OPTION){
                   dispose();
               }
           }});

问题是 a==OK_OPTIONa==CANCEL_OPTION 框架将关闭。

为什么?

最佳答案

您可能已将 JFrame 的默认关闭操作设置为 EXIT_ON_CLOSE。因此,无论您按 OK 还是 CANCEL,都会退出 JFrame。如果您想手动处理 JFrame 的关闭操作,则应将默认关闭操作设置为 DO_NOTHING_ON_CLOSE

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
               int a = JOptionPane.showConfirmDialog(null, 
                            "Are you sure you want to exit the program?", "Exit Program ",
                            JOptionPane.YES_NO_OPTION);
               System.out.println(a);
               if(a==JOptionPane.OK_OPTION){
                   dispose();//You can use System.exit(0) if you want to exit the JVM
               }
           }});

关于java - 为什么用ConfirmDialog关闭Frme窗口会在两种情况下(确定和取消)关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15718165/

相关文章:

java - 我想问一下《Java面向对象编程简介》(第五版)中的练习11(二级编程练习)

java - HTML 输出未在 JEditorPane 中正确显示

带双显示器的 Java 全屏 jframe

java - 清理并构建 NetBeans 错误

java - java swing中的简单可滚动文本区域

java - Jframe 顶部的 Facebook 蓝色背景

java - 将 java bean 序列化为 cookie : Is it bad?

java - 该算法会生成加密安全的比特流吗?

java - 在 Java 中重新安排计时器

java - Swing - 删除选定的边框并更改 JComboBox 的箭头颜色