【问题标题】:JOptionPane YES/No Options Confirm Dialog Box IssueJOptionPane YES/No 选项确认对话框问题
【发布时间】:2012-01-31 03:02:10
【问题描述】:

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

    }
}

【问题讨论】:

    标签: java swing jfilechooser


    【解决方案1】:

    您需要查看对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,但我并没有很好地理解它。但是现在有了我的错误和你的解释,它消除了很多混乱。我会更多地玩这个,看看我能想出什么。谢谢!!!
    • @iMohammad,你为什么不阅读 Swing 教程?本教程包含工作示例,适用于您过去几天提出的所有问题。
    【解决方案2】:

    试试这个,

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

    【讨论】:

    • 我可以用什么代替this?我在静态环境中执行此操作。
    • 您可以将null 放在屏幕中间而不是父框架的中心。
    【解决方案3】:
    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");
    }
    

    【讨论】:

    • 这与很久以前发布的the accepted answer 有何不同,因为使用JOptionPane.YES_OPTION 而不是0 更好?
    猜你喜欢
    • 2012-08-31
    • 2016-02-02
    • 2012-03-02
    • 2012-12-18
    • 2012-11-08
    • 1970-01-01
    • 2012-05-19
    • 2011-08-01
    • 1970-01-01
    相关资源
    最近更新 更多