我有一个JFrame,我想按";X〃;键(关闭JFrame(来确认我是否真的想关闭应用程序。如果我点击";"否";,它关闭应用程序。
如果我选择";否";?
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt){
if (JOptionPane.showConfirmDialog(rootPane, "Confirm out?",
"AppLocal", JOptionPane.ERROR_MESSAGE) == JOptionPane.ERROR_MESSAGE){
dispose();
}
}
});
在此处输入图像描述
在此处输入图像描述
方法:int javax.swing.JOptionPane.showConfirmDialog(Component parentComponent, Object message, String title, int optionType) throws HeadlessException
在optionType参数中,您必须使用:
JOptionPane.YES_NO_OPTION
JOptionPane.YES_NO_CANCEL_OPTION
JOptionPane.OK_CANCEL_OPTION
可用的返回值为:
//
// Return values.
//
/** Return value from class method if YES is chosen. */
public static final int YES_OPTION = 0;
/** Return value from class method if NO is chosen. */
public static final int NO_OPTION = 1;
/** Return value from class method if CANCEL is chosen. */
public static final int CANCEL_OPTION = 2;
/** Return value form class method if OK is chosen. */
public static final int OK_OPTION = 0;
/** Return value from class method if user closes window without selecting
* anything, more than likely this should be treated as either a
* <code>CANCEL_OPTION</code> or <code>NO_OPTION</code>. */
public static final int CLOSED_OPTION = -1;
因此,您的代码可以是:
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
if (JOptionPane.showConfirmDialog(rootPane, "Confirm out?",
"AppLocal", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION
) {
dispose();
}
}
});