public static int clickOnExit() {
int dialogButton=JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog(null, sharedConstants.exitMessage,"Confirm",dialogButton);
if(dialogButton == JOptionPane.YES_OPTION){return JFrame.EXIT_ON_CLOSE;}
else{return JFrame.DO_NOTHING_ON_CLOSE;}
}
确认(是)它可以工作,但我不确定取消选项是否正确解决。我只想取消JOptionPane并保持框架打开。
答案 0 :(得分:2)
你需要做三件事:
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
WindowListener
活动的windowClosing
。frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { maybeExit(); // Will not return if user clicks yes. super.windowClosing(e); } });
System.exit
的代码。private void maybeExit() { int yesNo = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (yesNo == JOptionPane.YES_OPTION) { System.exit(0); } }
答案 1 :(得分:0)
有些建议很有用。我用这种方式解决了它:
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (HandlingDialogBox.clickOnExit(frame) == 0) {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
} else {
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
});
}
和
public static int clickOnExit(final JFrame frame) {
return JOptionPane.showConfirmDialog(frame,sharedConstants.exitMessage,"Confirm",
JOptionPane.YES_NO_OPTION);
}
对于有点凌乱的括号使用,请稍后清理它......