confirmation before press YES to exit program in Java

社会主义新天地 提交于 2020-01-12 06:23:52

问题


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???


回答1:


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 ActionListener and action performed method.

check question - Java - Message when closing JFrame Window




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/21330682/confirmation-before-press-yes-to-exit-program-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!