To set the file filter for JFileChooser, you can use the setFileFilter() method of the JFileChooser class.
Here's an example code snippet that sets a file filter to display only text files:
JFileChooser fileChooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("Text files", "txt");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
} else {
System.out.println("No file selected.");
}
In the above code, a FileNameExtensionFilter object is created with the description "Text files" and the file extension "txt". Then, setFileFilter() method is used to set the file filter for JFileChooser. When the file chooser dialog is displayed, only files with the "txt" extension will be displayed.
You can create and set a custom file filter based on your specific file type or criteria by implementing the FileFilter interface and overriding the accept() and getDescription() methods.