[英]showOpenDialog() again if opened file is not XML
我制作了一个简单的应用程序,使用JFileChooser
仅打开XML文件。 如何反复显示打开的对话框,直到打开正确的XML文件或按“取消”按钮?
您可以将文件过滤器添加到文件选择器,以检查文件是否为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);
此循环执行以下操作:
继续打开对话框,直到按“取消”或选择有效文件为止。 您必须自己实现isValidFile:
do {
int returnVal = chooser.showOpenDialog(parent);
} while (returnVal != JFileChooser.CANCEL_OPTION || !isValidFile(chooser.getSelectedFile()));
该解决方案如何解决:它打开filechooser并检查它是否不是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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.