import javax.swing.JOptionPane;
import javax.swing.JFrame;
/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure you want to close this window?", "Close Window?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…