问题描述
我有一个 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();
}
}
});