这是我的代码:
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();
}
}});
问题是 a==OK_OPTION
或 a==CANCEL_OPTION
框架将关闭。
为什么?
最佳答案
您可能已将 JFrame
的默认关闭操作设置为 EXIT_ON_CLOSE
。因此,无论您按 OK
还是 CANCEL
,都会退出 JFrame
。如果您想手动处理 JFrame
的关闭操作,则应将默认关闭操作设置为 DO_NOTHING_ON_CLOSE
。
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
}
}});
关于java - 为什么用ConfirmDialog关闭Frme窗口会在两种情况下(确定和取消)关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15718165/