Search code examples
javaswingjfilechooserfilefilter

Simple JFileChooser FileFilter not working


The following is a simple code for saving a file on a user input directory using a JFileChooser derived from this as suggested by this answer from another stackoverflow question. However, this code will not work as intended as the file filter does not display all the defined filters.

public static void main(String[] args) {
    JFrame main = new JFrame();

    JButton saveto = new JButton("save");
    saveto.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) 
        { 
            JFileChooser chooser = new JFileChooser();
            int retval = chooser.showDialog(chooser, "Save");

            FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
            chooser.setFileFilter(filter);

            if (retval == JFileChooser.APPROVE_OPTION) 
            {
                File f_sample = chooser.getSelectedFile();
                System.out.println(f_sample + ".csv");
            }
        }
    });

    main.add(saveto);
    main.setSize(300,300);
    main.setLocationRelativeTo(null);
    main.setVisible(true);
    main.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}

The file f_sample also will contain null but removing the filter will cause the file f_sample to work as intended, containing the file selected. So I assumed that the cause of the malfunction is on the FileFilter

What is wrong with the file filter? And how can I make it work? Note that the code is from the Oracle Tutorial with a small modification.

Last minute modification

So I used chooser.addChoosableFileFilter(filter); instead of chooser.setFileFilter(filter); and the file f_sample now contains the file defined by the user. However, the defined filters will still not show on the JFileChooser window.


Solution

  • You are showing your chooser before setting the filter

    change to

    JFileChooser chooser = new JFileChooser();
    
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", 
                                                                            "jpg", "gif");
    chooser.setFileFilter(filter);
    int retval = chooser.showDialog(chooser, "Save");
    
    // etc