选项窗格独立于选择停止程序
Option pane stopping the program independently of the choice
所以,我有一个 JOptionPane,当我单击 JFrame 的 "red X" 时,会弹出确认对话框。问题是,无论我选择什么,它都会停止程序。单击 "NO" 时如何无法停止程序?
此外,如果我打开了两个框架,我如何创建它以仅关闭选定的框架?因为它正在关闭两个框架。
if (JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
System.exit(0);
}
首先你需要设置
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
然后您需要像这样向您的框架添加一个 WindowListener:
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
if (JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
System.exit(0);
}
}});
如果你有 2 个框架,但你只需要关闭一个,你可以使用 frame.dispose();
而不是 System.exit(0);
您应该通过与适当的枚举进行比较来检查 showConfirmDialog 的结果(返回的值不是布尔值)
int userChoice = JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing", JOptionPane.YES_NO_OPTION);
if (userChoice == JOptionPane.YES_OPTION) {
window.dispose();
}
所以,我有一个 JOptionPane,当我单击 JFrame 的 "red X" 时,会弹出确认对话框。问题是,无论我选择什么,它都会停止程序。单击 "NO" 时如何无法停止程序?
此外,如果我打开了两个框架,我如何创建它以仅关闭选定的框架?因为它正在关闭两个框架。
if (JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
System.exit(0);
}
首先你需要设置
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
然后您需要像这样向您的框架添加一个 WindowListener:
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
if (JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
System.exit(0);
}
}});
如果你有 2 个框架,但你只需要关闭一个,你可以使用 frame.dispose();
而不是 System.exit(0);
您应该通过与适当的枚举进行比较来检查 showConfirmDialog 的结果(返回的值不是布尔值)
int userChoice = JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Confirm closing", JOptionPane.YES_NO_OPTION);
if (userChoice == JOptionPane.YES_OPTION) {
window.dispose();
}