简体   繁体   中英

How to add file filter for JFileChooser

I want to select only .xls and .xlsx file but I am unable to select any type of file. Can anybody suggest me any code or can anybody make changes in my existing code ? Thanks in advance.

    public class Convertor {
    public static void main(String[] args) {
    JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("choosertitle");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
          System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
          System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
        } else {
          System.out.println("No Selection ");
        }
     }
}    

You should use FileNameExtensionFilter .

 FileFilter filter = new FileNameExtensionFilter("Excel file", "xls", "xlsx");
 chooser.addChoosableFileFilter(filter);

You can also use FileFilter class.

class ExcelFilter extends FileFilter {

@Override
public boolean accept(File pathname) {
  String filename = pathname.getName();
  if (pathname.isDirectory()) {
    return true;

  } else if (filename.endsWith("xls") || filename.endsWith("xlsx")) {
    return true;
  } else {
    return false;
  }
}

@Override
public String getDescription() {
  return "Excel Files";
}
}

Now in your main class use:

chooser.setFileFilter(new ExcelFilter());

Improving @Amila's comment, it should be something like this:

 FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files", "xlsx", "xls");
 fileChooser.addChoosableFileFilter(filter);            
 fileChooser.setFileFilter(filter);

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