Pages

Set file type in JFileChooser

Complete source code below will show you, how set file type that should be display in a JFileChooser. Source code below will display all directories and text files only.

***************************************************************************
COMPLETE SOURCE CODE FOR : SetJFileChooserFileType.java
***************************************************************************


import javax.swing.filechooser.FileFilter;

import javax.swing.JFileChooser;

import java.io.File;

public class SetJFileChooserFileType
{
public SetJFileChooserFileType()
{
//Create a file chooser from JFileChooser
JFileChooser fileChooser=new JFileChooser();

//Set file type that should be display by set JFileChooser's file filter
fileChooser.setFileFilter(new TypeOfFile());

//Show JFileChooser
int a=fileChooser.showDialog(null,"Open Text File");
}

//Class TypeOfFile
class TypeOfFile extends FileFilter
{
//Type of file that should be display in JFileChooser will be set here
//We choose to display only directory and text file
public boolean accept(File f)
{
return f.isDirectory()||f.getName().toLowerCase().endsWith(".txt");
}

//Set description for the type of file that should be display
public String getDescription()
{
return ".text files";
}
}

public static void main(String[]args)
{
SetJFileChooserFileType sjfcft=new SetJFileChooserFileType();
}
}


***************************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************************
Related Posts Plugin for WordPress, Blogger...