2011-12-31 30 views
48

我创建了一个JOptionPane,它只有两个按钮YES_NO_OPTIONJOptionPane的选择Yes/No确认对话框问题

经过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) { 

    } 
} 

回答

89

你需要看调用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可能永远都没有什么比​​等。

每的Javadoc showConfirmDialog

返回:一个整数,指示用户

+0

哇它的工作!我刚开始使用'showConfirmDialog',我没有得到它这么好,虽然我读的Javadoc。但是现在我的错误和你的解释清除了很多混乱。我会更多地玩这个游戏,看看我能想出什么。谢谢!!! – Sobiaholic 2011-12-31 16:24:00

+3

@iMohammad,你为什么不读了Swing教程?本教程包含工作示例,针对您在过去几天中提出的所有问题。 – camickr 2011-12-31 16:41:30

+1

链接camickr的建议:http://docs.oracle.com/javase/tutorial/uiswing/ – ziesemer 2011-12-31 16:43:23

26

试试这个选择的选项,

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

我可以把什么,而不是'this'?我在静态环境中这样做。 – 2018-02-15 04:27:44

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