简体   繁体   English

如果打开的文件不是XML,则再次显示showOpenDialog()

[英]showOpenDialog() again if opened file is not XML

I made a simple application to open only XML files using JFileChooser . 我制作了一个简单的应用程序,使用JFileChooser仅打开XML文件。 How can I show the open dialog again and again until I open correct XML file or press cancel button? 如何反复显示打开的对话框,直到打开正确的XML文件或按“取消”按钮?

You could add a file filter to the file chooser that checks whether the file is an xml file. 您可以将文件过滤器添加到文件选择器,以检查文件是否为xml文件。

When the user has selected a file you check that file's content and if it isn't valid you just open the filechooser again, eg in a loop that exits when either the file is valid or the user selected the cancel option. 用户选择文件后,您将检查该文件的内容,如果文件无效,则只需再次打开文件选择器即可,例如,在文件有效或用户选择了取消选项时退出的循环中。

Basically the loop might look like this (that's quickly written and might contain errors): 基本上,循环可能看起来像这样(快速编写并可能包含错误):

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

This loop does the following: 此循环执行以下操作:

  • it opens the filechooser and gets the selected option 它打开文件选择器并获取选定的选项
  • 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, eg CANCEL, was selected or the file is valid) 当选择“确定”选项但所选文件无效时,进行另一次迭代-否则结束循环(如果选择了另一个选项(例如“取消”)或文件有效)

Keep opening the dialog until cancel is pressed or a valid file is chosen. 继续打开对话框,直到按“取消”或选择有效文件为止。 You have to implement isValidFile yourself: 您必须自己实现isValidFile:

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

What about this Solution: It open filechooser and checks if it was not a CANCEL_OPTION. 该解决方案如何解决:它打开filechooser并检查它是否不是CANCEL_OPTION。 If your check for the correct XML File was successful, then you break the while loop. 如果对正确的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;   
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM