confirmation before press YES to exit program in Java

21,161

Solution 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

Solution 2

JFrame frame = new JFrame();

// ...

frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
        int resp = JOptionPane.showConfirmDialog(frame, "Are you sure you want to exit?",
            "Exit?", JOptionPane.YES_NO_OPTION);

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

Solution 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);
Share:
21,161
jefferyleo
Author by

jefferyleo

Updated on March 29, 2021

Comments

  • jefferyleo
    jefferyleo about 3 years
    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???