在按 YES 退出 Java 程序之前确认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21330682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:05:31  来源:igfitidea点击:

confirmation before press YES to exit program in Java

javaswingwindowjframejoptionpane

提问by jefferyleo

private void windowClosing(java.awt.event.WindowEvent evt)                               
    {                                   
        int confirmed = JOptionPane.showConfirmDialog(null, "Exit Program?","EXIT",JOptionPane.YES_NO_OPTION);
        if(confirmed == JOptionPane.YES_OPTION)
        {
            dispose();
        }
    }

I want to close program by pressing Close Window Button with confirmation...But when I choose "No" to back to my Jframe, it still helps me to exit the program???

我想通过按下关闭窗口按钮并确认来关闭程序......但是当我选择“否”返回我的 Jframe 时,它​​仍然可以帮助我退出程序???

采纳答案by Tomas Bisciak

From what i understand you want something like this

据我了解你想要这样的东西

addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
    int confirmed = JOptionPane.showConfirmDialog(null, 
        "Are you sure you want to exit the program?", "Exit Program Message Box",
        JOptionPane.YES_NO_OPTION);

    if (confirmed == JOptionPane.YES_OPTION) {
      dispose();
    }
  }
});

If you want to use it on some button do similiar function to button. Put listener on it and do same. But I'm not sure if I get your question right. But If you want to use button use ActionListenerand action performedmethod.

如果您想在某个按钮上使用它,请执行与按钮类似的功能。把听众放在上面并做同样的事情。但我不确定你的问题是否正确。但是如果要使用按钮,请使用ActionListener操作执行方法。

check question - Java - Message when closing JFrame Window

检查问题 - Java - 关闭 JFrame 窗口时的消息

回答by homesh

Try this, it's working for me.

试试这个,它对我有用。

private void windowClosing(java.awt.event.WindowEvent evt) {                                   
    int confirmed = JOptionPane.showConfirmDialog(null, "Exit Program?","EXIT",JOptionPane.YES_NO_OPTION);
    if(confirmed == JOptionPane.YES_OPTION)
    {
        dispose();
    }
} else {
     setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

回答by Udeesha Induwara

addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent evt){
                int x = JOptionPane.showConfirmDialog(null, 
                    "Are you sure you want to exit ?", "Comform !",
                    JOptionPane.YES_NO_OPTION);

                if(x == JOptionPane.YES_OPTION) {
                    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                }else{
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                }
            }
        });

Chek this.

查这个。