Wednesday, October 15, 2014

JFileChooser with multiple FileFilters


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;
class FileTypeFilter extends FileFilter
{
    private String extension;
    private String description;

    public FileTypeFilter(String extension, String description)
    {
        this.extension = extension;
        this.description = description;
    }

    public boolean accept(File file)
    {
        if (file.isDirectory()) {
            return true;
        }
        return file.getName().endsWith(extension);
    }

    public String getDescription()
    {
        return description + String.format(" (*%s)", extension);
    }
}
class JFCtest extends JFrame implements ActionListener
{
    JButton jb1;
    JFileChooser fileChooser;
   
    public JFCtest()
    {
        super("JFileChooser MultiFilters");
        setSize(300,100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(new JPanel().add(jb1=new JButton("Open")));
        jb1.addActionListener(this);
        setVisible(true);
       

    }
    public void actionPerformed(ActionEvent e)
    {
        fileChooser =new JFileChooser();
        fileChooser.setCurrentDirectory(new File("D:\\myjava"));
        FileFilter jpgFilter = new FileTypeFilter(".jpg", "JPEG Image");
        FileFilter txtFilter = new FileTypeFilter(".txt", "Text File");
        FileFilter javaFilter = new FileTypeFilter(".java", "Java File");

        
        fileChooser.addChoosableFileFilter(jpgFilter);
        fileChooser.addChoosableFileFilter(txtFilter);
        fileChooser.addChoosableFileFilter(javaFilter);
        int result = fileChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION)
        {
                File selectedFile = fileChooser.getSelectedFile();
                    System.out.println("Selected file: " + selectedFile.getAbsolutePath());
                }
    }
    public static void main(String args[])
    {
        try {
                    // Set System L&F
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }   catch (UnsupportedLookAndFeelException e) {// handle exception
                                  }
                catch (ClassNotFoundException e) {// handle exception
                             }
                catch (InstantiationException e) {// handle exception
                             }
            catch (IllegalAccessException e) {// handle exception
                             }
        new JFCtest();
    }
}