【问题标题】:showOpenDialog() again if opened file is not XML如果打开的文件不是 XML,则再次显示 OpenDialog()
【发布时间】:2012-02-01 13:41:18
【问题描述】:

我做了一个简单的应用程序,使用JFileChooser 只打开 XML 文件。在打开正确的 XML 文件或按下取消按钮之前,如何一次又一次地显示打开的对话框?

【问题讨论】:

    标签: java swing user-interface jfilechooser


    【解决方案1】:

    您可以在文件选择器中添加一个文件过滤器,以检查文件是否为 xml 文件。

    当用户选择了一个文件时,您检查该文件的内容,如果它无效,您只需再次打开文件选择器,例如在文件有效或用户选择取消选项时退出的循环中。

    基本上循环可能看起来像这样(写得很快并且可能包含错误):

    int option = CANCEL_OPTION;
    boolean fileIsValid = false;
    do {
     option = filechooser.showOpenDialog(); //or save?
     if( option == OK_OPTION ) {
        fileIsValid = isValid( filechooser.getSelectedFile()); //implementation of isValid() is left for you
     }
    } while( option == OK_OPTION && !fileIsValid);
    

    此循环执行以下操作:

    • 它会打开文件选择器并获取选定的选项
    • when the OK option is selected the selected file is checked
    • when the OK option was selected but the selected file is invalid, do another iteration - otherwise end the loop (if another option, e.g. CANCEL, was selected or the file is valid)

    【讨论】:

      【解决方案2】:

      继续打开对话框,直到按下取消或选择有效文件。你必须自己实现 isValidFile:

      do {
          int returnVal = chooser.showOpenDialog(parent);
      } while (returnVal != JFileChooser.CANCEL_OPTION || !isValidFile(chooser.getSelectedFile()));
      

      【讨论】:

        【解决方案3】:

        这个解决方案怎么样: 它打开文件选择器并检查它是否不是 CANCEL_OPTION。如果您对正确 XML 文件的检查成功,那么您 break while 循环。

            JFileChooser fc = new JFileChooser();
            int returnVal = -1;
        
            while (returnVal != JFileChooser.CANCEL_OPTION) {
                returnVal = fc.showOpenDialog(putYourParentObjectHere);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    if (doYourCheckIfCorrectXMLFileWasChosenHere) {
                        // do the stuff you want
                        break;   
                    }
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多