Question

I have a JButton that needs to open a file of a specific extension. In brief, I define a JButton add an actionlistener to it that fires a JFileChooser, if JButton is clicked. I want to add a file filter so that only files of extension .mpg will be shown on the JFileChooser.

The compilation shows no errors, but on the swing the JFileChooser shows no filtering of the available files (nor the option 'Movie files' in the combobox appears - just 'All files'). In two words, it seems that addChoosableFileFilter has no effect whatsoever.

My code is:

final JFileChooser jfc = new JFileChooser(moviedir);
//add File Filter
jfc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Movie files (*.mpg)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {return true;} 
else {return f.getName().toLowerCase().endsWith(".mpg");}
 }
});

I have also tried the alternative of

jfc.addChoosableFileFilter(new FileNameExtensionFilter("Movie files", "mpg"));

with the same fate. All the above are on JPanel of a JFrame of my swing.

I 've read many related threads but no luck.

Thanks in advance for comments.

Was it helpful?

Solution

JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser, see How to Use File Choosers, a section in The Java Tutorial.

The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

Try this. Copied from here

OTHER TIPS

Try this code. It worked for me

call your filechooser like this:-

JFileChooser fc = new JFileChooser("C:/");
            fc.setFileFilter(new JPEGImageFileFilter());

and make class JPEGImageFileFilter like this:-

 class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter
         {
         public boolean accept(File f)
           {
           if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
           if (f.getName().toLowerCase().endsWith(".jpg")) return true;
           if (f.getName().toLowerCase().endsWith(".avi")) return true;
           if (f.getName().toLowerCase().endsWith(".mpeg")) return true;
           return false;
           }
         public String getDescription()
           {
           return "JPEG files";
           }

         }

simple...

jfc.setFileFilter(new FileNameExtensionFilter("Movie files", "mpg"));

Just provide an example for reference.

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import java.text.*;

public class TextReaderExapmle extends JFrame {

    private static final long serialVersionUID = -8816650884305666302L;
    private static final String FRAME_TITLE = "File Chosser demo";
    private static final Dimension FRAME_SIZE = new Dimension(400, 350);
    private JButton fileChoosingButton;
    private JTextArea textArea;
    private JFileChooser fileChooser;

    public TextReaderExapmle() {
        super(FRAME_TITLE);
        init();
        doLay();
        attachListeners();
    }

    private void init() {
        fileChoosingButton = new JButton(new FileChooseAction());
        textArea = new JTextArea();

        fileChooser = new JFileChooser(System.getProperty("user.dir"));
        fileChooser.setFileFilter(new TextFileFilter());
        fileChooser.setMultiSelectionEnabled(false);
    }

    private void doLay() {
        Container container = getContentPane();
        container.add(fileChoosingButton, BorderLayout.NORTH);
        container.add(new JScrollPane(textArea), BorderLayout.CENTER);

        setSize(FRAME_SIZE);
        setVisible(true);
    }

    private void attachListeners() {
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(1);
            }
        });
    }

    /**
     * read text from the selected text file and convert text to string
     * 
     * @param reader
     * @return converted string
     */
    private static String readTextFromFile(final FileReader reader) {
        if (reader == null)
            return "";
        StringBuffer buf = new StringBuffer();

        final int CACHE_SIZE = 1024;
        final char[] cache = new char[CACHE_SIZE];
        try {
            int b;
            while ((b = reader.read(cache)) != -1) {
                if (b < CACHE_SIZE)
                    buf.append(cache, 0, b);
                else
                    buf.append(cache);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    /**
     * open file chooser action
     */
    private class FileChooseAction extends AbstractAction {
        static private final String ACTION_LABEL = "Open File...";

        public FileChooseAction() {
            super(ACTION_LABEL);
        }

        public void actionPerformed(ActionEvent e) {

            int returnVal = fileChooser.showOpenDialog(fileChoosingButton);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    FileReader reader = new FileReader(
                            fileChooser.getSelectedFile());
                    textArea.setText(readTextFromFile(reader));
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /* file filter */
    private class TextFileFilter extends FileFilter {
        private final java.util.List<String> fileNameExtensionList = new ArrayList<String>();

        public TextFileFilter() {
            fileNameExtensionList.add("txt");
            fileNameExtensionList.add("java");
            fileNameExtensionList.add("log");
            fileNameExtensionList.add("xml");
            fileNameExtensionList.add("htm");
            fileNameExtensionList.add("html");
            fileNameExtensionList.add("html");
            fileNameExtensionList.add("properties");
            fileNameExtensionList.add("svg");
        }

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

            if (lastIndexOfDot == -1)
                return false;

            int fileNameLength = fileName.length();
            final String extension = fileName.substring(lastIndexOfDot + 1,
                    fileNameLength);

            return fileNameExtensionList.contains(extension);
        }

        public String getDescription() {
            StringBuffer buf = new StringBuffer("Text File(");
            for (String fn : fileNameExtensionList)
                buf.append(MessageFormat.format("*.{0};", fn));
            return buf.append(')').toString();
        }
    }

    public static void main(String[] args) {
        new TextReaderExapmle();
    }
}

use following code and make it more readable and easy:

final JFileChooser jfc = new JFileChooser(moviedir);

jfc.addChoosableFileFilter(new FileNameExtensionFilter("*.mpg", "mpg"));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top