在创建JFileChooser文件选择器时,可选择指定文件格式,以选择excel文件为例:
- JFileChooser fc = new JFileChooser("."); //在当前目录下,创建文件选择器
- ExcelFileFilter excelFilter = new ExcelFileFilter(); //excel过滤器
- fc.addChoosableFileFilter(excelFilter);
- fc.setFileFilter(excelFilter);
- if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
- }
ExcelFileFilter:
- class ExcelFileFilter extends FileFilter {
- public String getDescription() {
- return "*.xls;*.xlsx";
- }
- public boolean accept(File file) {
- String name = file.getName();
- return file.isDirectory() || name.toLowerCase().endsWith(".xls") || name.toLowerCase().endsWith(".xlsx"); // 仅显示目录和xls、xlsx文件
- }
- }