当前位置: 代码迷 >> J2SE >> 请看代码,怎样可以让用户按下NO的时候窗口不关闭?该如何解决
  详细解决方案

请看代码,怎样可以让用户按下NO的时候窗口不关闭?该如何解决

热度:82   发布时间:2016-04-24 12:42:16.0
请看代码,怎样可以让用户按下NO的时候窗口不关闭?
Java code
class MyWindowAdapter extends WindowAdapter        {            public void windowClosing(WindowEvent e)            {                int flag = JOptionPane.showConfirmDialog(MainFrame.this, "Are you sure that you want to exit? " +                     "Any unsaved work will be lost! ", "Sure to exit?", JOptionPane.YES_NO_OPTION);                                if (flag == 0)    // User selected YES                    setVisible(false);                else if (flag == 1)    // User selected NO                    // ...            }        }                addWindowListener(new MyWindowAdapter());


如果用户点击左上角的那个小叉,就会弹出我定义的那个confirmDialog,但是不管我选YES还是NO,窗口最后都会关闭。有什么办法可以让这个Frame在选择NO后不关闭?

------解决方案--------------------
Java code
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Test extends JFrame{    public Test()    {        setSize(200, 200);        addWindowListener(new MyWindowAdapter());    }        public static void main(String[] args)    {        Test t = new Test();        t.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//你肯定落了这句        t.setVisible(true);    }        class MyWindowAdapter extends WindowAdapter    {        public void windowClosing(WindowEvent e)        {            int flag = JOptionPane.showConfirmDialog(Test.this, "Are you sure that you want to exit? " +                         "Any unsaved work will be lost! ", "Sure to exit?", JOptionPane.YES_NO_OPTION);            if (flag == JOptionPane.YES_OPTION)                Test.this.setVisible(false);        }    }}
  相关解决方案