我一直使用 JFileChooser 而不是 FileDialog。然后,您可以为您的程序将以这种方式支持的各种类型添加多个 ChoosableFileFilter:
File myFilename;
chooser = new JFileChooser();
chooser.addChoosableFileFilter(new OpenFileFilter("jpeg","Photo in JPEG format") );
chooser.addChoosableFileFilter(new OpenFileFilter("jpg","Photo in JPEG format") );
chooser.addChoosableFileFilter(new OpenFileFilter("png","PNG image") );
chooser.addChoosableFileFilter(new OpenFileFilter("svg","Scalable Vector Graphic") );
int returnVal = chooser.showSaveDialog(mainWindow);
if (returnVal == JFileChooser.APPROVE_OPTION) {
myFilename = chooser.getSelectedFile();
//do something with the file
}
下面是我对 FileFilter 的实现。
/**
* This class defines which file types are displayed (by default) by the JFileChooser and what file
* types appear in the drop down menu in the file dialog.
* You could add more than one file type to the open file dialog by creating multiple instances of this
* class and then repeatedly calling addFileFilter.
* @author LaSpina
*/
import java.io.File;
import javax.swing.filechooser.*;
public class OpenFileFilter extends FileFilter {
String description = "";
String fileExt = "";
public OpenFileFilter(String extension) {
fileExt = extension;
}
public OpenFileFilter(String extension, String typeDescription) {
fileExt = extension;
this.description = typeDescription;
}
@Override
public boolean accept(File f) {
if (f.isDirectory())
return true;
return (f.getName().toLowerCase().endsWith(fileExt));
}
@Override
public String getDescription() {
return description;
}
}