Creating a Text File Filter
The first step in creating a text file filter is to create a new class that extends the abstract class FileFilter. You will need to implement the accept() method and the getDescription() method.
The accept() method sends you a File object for each file in the directory. Since there could be a large number of files in a directory, you should keep this method simple and fast. For our text file filter example, we will simply check to see if the file name ends with a ".txt" extentions.
public boolean accept(File file)The getDescription() method will be the text that is displayed in the File Types combo box.
{
//Convert to lower case before checking extension
return file.getName().toLowerCase().endsWith(".txt");
}
public String getDescription()Below is the complete implementation of the TextFileFilter class.
{
return "Text File (*.txt)";
}
public class TextFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File file)
{
//Convert to lower case before checking extension
return file.getName().toLowerCase().endsWith(".txt");
}
public String getDescription()
{
return "Text File (*.txt)";
}
}
To use the TextFileFilter in your JFileChooser, use the addChoosableFileFilter() method as shown below:
fileChooser.addChoosableFileFilter(new TextFileFilter());Creating a Date File FilterNow that we have created a basic file filter, we are going to create a file filter that shows only the files that have been modified this month. To do so, we are going to compare the current month and year with the month and year of the file.
Below is the complete class for the DateFileFilter class:
public class DateFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File file)
{
//Get today's date
GregorianCalendar date = new GregorianCalendar();
//Get the date the file was modifed
GregorianCalendar fileDate = new GregorianCalendar();
fileDate.setTimeInMillis(file.lastModified());
//Compare the current month and year
//with the month and yearthe file was
//last modified
return ((date.get(GregorianCalendar.MONTH) == fileDate.get(GregorianCalendar.MONTH)) &&
(date.get(GregorianCalendar.YEAR) == fileDate.get(GregorianCalendar.YEAR)));
}
public String getDescription()
{
return "Modified This Month";
}
}
discuss this topic to forum
