java – JOptionPane是/否选项确认对话框问题
作者:互联网
我创建了一个JOptionPane,它只有两个按钮YES_NO_OPTION.
弹出JOptionPane.showConfirmDialog后,我想点击YES BUTTON继续打开JFileChooser,如果我点击NO BUTTON,它应该取消操作.
这似乎很容易,但我不确定我的错误在哪里.
代码片段:
if (textArea.getLineCount() >= 1) { //The condition to show the dialog if there is text inside the textArea
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if (dialogButton == JOptionPane.YES_OPTION) { //The ISSUE is here
JFileChooser saveFile = new JFileChooser();
int saveOption = saveFile.showSaveDialog(frame);
if(saveOption == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(saveFile.getSelectedFile().getPath()));
fileWriter.write(textArea.getText());
fileWriter.close();
} catch(Exception ex) {
}
}
解决方法:
您需要查看对showConfirmDialog的调用的返回值.即:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
// Saving code here
}
你正在测试dialogButton,你用它来设置对话框应该显示的按钮,而且这个变量从未更新过 – 所以dialogButton永远不会是JOptionPane.YES_NO_OPTION以外的任何东西.
根据showConfirmDialog的Javadoc:
Returns: an integer indicating the option selected by the user
标签:jfilechooser,java,swing 来源: https://codeday.me/bug/20190930/1834672.html