How to filter file type in FileDialog?

PinkiePie-Z picture PinkiePie-Z · Sep 24, 2012 · Viewed 24.2k times · Source

I am using FileDialog for saving and loading in a Java program.

How can I filter the dropdown list to specify the file type as "JPG" or "JPEG" etc. ?

I have tried the following code, but it seems to have no effect.

Are there any other ways of doing this ?

public void actionPerformed(ActionEvent e) {
            FileDialog saveFileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);

            saveFileDialog.setFilenameFilter(new FilenameFilter(){
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith(".jpg") || name.endsWith(".jpeg");
                }
            });
            saveFileDialog.setFile("Untitled.jpg");
            saveFileDialog.setVisible(true);
        }

Answer

swemon picture swemon · Sep 24, 2012

The answer is simple. You can use

 saveFileDialog.setFile("*.jpg;*.jpeg");

No need to use setFilenameFilter method. You can add as many file type as you which.

Solving of this problem can be found in huxhorn' s comment in Bug ID: 4031440 FileDialog doesn't call FilenameFilter.accept().

public void actionPerformed(ActionEvent e) {
            FileDialog saveFileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
            saveFileDialog.setFile("*.jpg;*.jpeg");
            saveFileDialog.setVisible(true);
        }