询问用户是否想通过JOptionPane退出

时间:2013-05-03 20:42:42

标签: java swing jframe joptionpane windowlistener

当我点击JFrame的红色交叉关闭按钮(右上角)时,我正在使用此代码确认用户是否要退出

 Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};

int Answer = JOptionPane.showOptionDialog(null, "What would you like to do? ","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
    null, options,options[1]);
    if(Answer == JOptionPane.YES_OPTION){

        System.exit(0); 
    }
    else if (Answer == JOptionPane.CANCEL_OPTION) {
        return;
    } 

但问题是如果用户单击CANCEL_OPTION框架关闭,但我希望用户仍然打开框架并且不允许框架关闭。引导我如果我在犯错误或其他什么?

4 个答案:

答案 0 :(得分:2)

这样做:

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

答案 1 :(得分:2)

您可以尝试这样的事情:

    import javax.swing.*;
    import java.awt.event.*;
    public class MyFrame extends JFrame
    {
        public MyFrame()
        {
            setTitle("Close Me");
            setSize(200,200);
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            addWindowListener(new WindowAdapter()
            {
                    @Override
                    public void windowClosing(WindowEvent evt)
                    {
                        Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};

                        int answer = JOptionPane.showOptionDialog(MyFrame.this, "What would you like to do? ","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                                     null, options,options[1]);
                        if(answer == JOptionPane.YES_OPTION)
                        {
                            System.exit(0); 
                        }
                    }
            });
        }
        public static void main(String st[])
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    MyFrame mf = new MyFrame();
                    mf.setVisible(true);
                }
            });
        }
    }

作为旁注,我建议你坚持使用java命名约定。例如,变量名称永远不应以大写字母开头,类名应始终以大写字母开头..还有更多。看看这里 Code Conventions for the Java Programming Language

答案 2 :(得分:0)

我有一个真正的错误

   Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};

   int Answer = JOptionPane.showOptionDialog(null, "What would you like to do?","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options,options[1]);
if(Answer == JOptionPane.YES_OPTION){

    System.exit(0); 
}
else if (Answer == JOptionPane.CANCEL_OPTION) {
    return;
} 

很明显,我有两个选项,即YES_NO_OPTION,我正在调用CANCEL_OPTION,这是一个真正的错误,所以,else-if应该更改为:

else if (Answer == JOptionPane.NO_OPTION) {
    this.setDefaultCloseOperation(myclassreference.DO_NOTHING_ON_CLOSE);
} 

之后;它的宾果!我做完了!

答案 3 :(得分:0)

尝试这样的事情:

{
...
yourFrame.setDefaultCloseOperation(close());
...
}

private int close() {
if(yourCondition)
    return JFrame.DO_NOTHING_ON_CLOSE;
else 
    return JFrame.EXIT_ON_CLOSE;
}