JOptionPane YES/No选项确认对话框问题

71

我创建了一个 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) {

    }
}
3个回答

122

你需要查看调用 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:

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


哇,它起作用了!我刚开始使用showConfirmDialog,虽然我读了Javadoc,但我并没有完全理解。但现在通过我的错误和你的解释,它消除了很多困惑。我会更多地尝试这个功能,并看看能得到什么。谢谢! - Sobiaholic
3
@iMohammad,为什么你不读一下Swing教程呢?教程中包含了大量可供参考的实例,可以回答你过去几天中所提出的所有问题。 - camickr

44

试试这个,

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");
} 

1
我在静态上下文中进行操作,我可以用什么代替“this”? - Aaron Franke
1
你可以放置 null,这样对话框就会居中显示在屏幕上,而不是父窗口。 - Mike

7
int opcion = JOptionPane.showConfirmDialog(null, "Realmente deseas salir?", "Aviso", JOptionPane.YES_NO_OPTION);

if (opcion == 0) { //The ISSUE is here
   System.out.print("si");
} else {
   System.out.print("no");
}

1
这与早先发布的被接受的答案有何不同?那个答案更好,因为使用了JOptionPane.YES_OPTION而不是0 - derHugo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接