按YES之前确认退出Java程序

时间:2014-01-24 10:49:12

标签: java swing window jframe joptionpane

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

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

3 个答案:

答案 0 :(得分:9)

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。

答案 1 :(得分:5)

根据我的理解,你想要这样的东西

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

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

检查问题 - Java - Message when closing JFrame Window

答案 2 :(得分:1)

试试这个,它对我有用。

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