为什么Frme windowClosing与ConfirmDialog关闭两种情况(OK& Cancel)?

时间:2013-03-30 11:45:24

标签: 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框架将关闭。

为什么?

1 个答案:

答案 0 :(得分:2)

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

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
               }
           }});