JOptionPane是/否选项确认对话框发布-Java

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (51)

我创建了一个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。IE:

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

根据Javadoc为showConfirmDialog

返回:表示用户选择的选项的整数

用户回答回答于

尝试这个,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

扫码关注云+社区