简体   繁体   中英

showOpenDialog() again if opened file is not XML

I made a simple application to open only XML files using JFileChooser . How can I show the open dialog again and again until I open correct XML file or press cancel button?

You could add a file filter to the file chooser that checks whether the file is an xml file.

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:

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. If your check for the correct XML File was successful, then you break the while loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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