0

我正在使用此代码来确认用户在单击 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

4 回答 4

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 命名约定。例如变量名不应该以大写字母开头,类名应该总是以大写字母开头..等等。在这里查看 Java 编程语言的代码约定

于 2013-05-03T20:57:09.843 回答
2

这样做:

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
于 2013-05-03T20:45:10.280 回答
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);
} 

在这之后; 它的宾果游戏!我已经搞定了!

于 2013-05-03T20:54:12.130 回答
0

尝试这样的事情:

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

private int close() {
if(yourCondition)
    return JFrame.DO_NOTHING_ON_CLOSE;
else 
    return JFrame.EXIT_ON_CLOSE;
}
于 2013-05-03T21:00:17.573 回答