Close a JFrame under condition
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Main extends JFrame { public Main() { setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) { } public void windowClosing(WindowEvent e) { if (JOptionPane.showConfirmDialog(null, "Are you sure ?") == JOptionPane.YES_OPTION) { setVisible(false); dispose(); } } }); pack(); setVisible(true); } public static void main(String args[]) { new Main(); } }