here is my code :
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the program?", "Exit Program ",
JOptionPane.YES_NO_OPTION);
System.out.println(a);
if(a==JOptionPane.OK_OPTION){
dispose();
}
}});
The problem is either a==OK_OPTION
or a==CANCEL_OPTION
the frame will close.
Why?
You might have set the default close operation of JFrame
as EXIT_ON_CLOSE
. So this exits the JFrame
no matter if you press OK
or CANCEL
. You should instead set the default close operation as DO_NOTHING_ON_CLOSE
if you want to manually handle the close operation of your JFrame
.
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the program?", "Exit Program ",
JOptionPane.YES_NO_OPTION);
System.out.println(a);
if(a==JOptionPane.OK_OPTION){
dispose();//You can use System.exit(0) if you want to exit the JVM
}
}});