Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
108 views
in JAVA by (178k points)
How do I set the file filter for JFileChooser?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked May 11, 2023 in JAVA by kvdevika (178k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...