Java add file filter for jfilechooser dialog

www.ig‮ditfi‬ea.com

When you use a JFileChooser dialog in Java, you can add a file filter to restrict the types of files that the user can select. Here is an example of how to add a file filter to a JFileChooser:

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooserExample {
    public static void main(String[] args) {
        JFileChooser fileChooser = new JFileChooser();

        // Create a file filter for text files
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
        fileChooser.setFileFilter(filter);

        // Show the dialog and get the selected file
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            System.out.println("Selected file: " + fileChooser.getSelectedFile());
        }
    }
}

In this example, we create a JFileChooser instance and then create a FileNameExtensionFilter that restricts the user to selecting files with a ".txt" extension. We then call the setFileFilter() method on the JFileChooser instance and pass in the filter as an argument.

When the user opens the file dialog, they will only see files with the ".txt" extension. If they select a file with a different extension, the dialog will not allow them to choose it.

Once the user selects a file, the showOpenDialog() method returns either JFileChooser.APPROVE_OPTION or JFileChooser.CANCEL_OPTION, depending on whether the user clicked the "Open" or "Cancel" button. If they clicked "Open", we can retrieve the selected file using the getSelectedFile() method.

Note that you can create multiple file filters and add them to the JFileChooser using the addChoosableFileFilter() method. You can also use the setAcceptAllFileFilterUsed() method to enable or disable the default "All Files" filter.