Thursday, May 08, 2008

Filter file(s) in JFileChooser

JFileChooser is one of the most important components when we talk about Swing application from small to big size applications. Most of the time we write the code of JFileChooser on a button listener aka open a file on button name Open, so code will go :

open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int returnVal = fc.showOpenDialog(FileChooserFrame);
//do action according to the value of returnVal
................

But its always better to put a filter on a specific type of file which is required. Most of the time user don't required all types of files. Say, he need only .avi files or .mov files. Thens its a good idea to put a filter which will give only .avi or .mov files in the file chooser option. Month back, I had written one small code which do filtering for .java and .sh files and here it is:

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;

class JtregFilter extends FileFilter {

public boolean accept(File f) {
if (f.isDirectory())
return true;
String s = f.getName();
int i = s.lastIndexOf('.');

if (i > 0 && i < s.length() - 1)
if (s.substring(i + 1).toLowerCase().equals("java" ) || s.substring(i + 1).toLowerCase().equals("sh" ))
return true;

return false;
}

public String getDescription() {
return "*.java, *.sh";
}
}

Now nothing need to do in listener except adding one more line :

open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
fc.addChoosableFileFilter(new JtregFilter());
int returnVal = fc.showOpenDialog(FileChooserFrame);
//do action according to the value of returnVal
...................

and we are done. Now JFileChooser will only show me folders and file with extension .java or .sh. Worthwhile to write a small code for user ease.

No comments: