JFileChooser
Select file selection mode in file chooser
With this tutorial we are going to see how to set the file selection mode in a file chooser of a Java Desktop Application. This is very useful when you want to search for a specific type of file in your file system.
To select file selection mode in a file chooser in a Java Application you have to:
- Create a new
JFrame
. - Create a new
JFileChooser
to aFile
. - Call
setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
. This will list only directories. - Call
setFileSelectionMode(JFileChooser.FILES_ONLY)
. This will list only files. - Call
setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES)
. This will list both files and directories. - Use
showOpenDialog
to pop up an Open File Chooser dialog.
Let’s see the code:
package com.javacodegeeks.snippets.desktop; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; public class SelectFileSelectionModeInFileChooser { private static final long serialVersionUID = 1L; private static void createAndShowGUI() { // Create and set up the window. final JFrame frame = new JFrame("Centered"); // Display the window. frame.setSize(200, 200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set flow layout for the frame frame.getContentPane().setLayout(new FlowLayout()); JButton button = new JButton("Choose file/directory"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createFileChooser(frame); } }); frame.getContentPane().add(button); } private static void createFileChooser(final JFrame frame) { String filename = File.separator+"tmp"; JFileChooser fileChooser = new JFileChooser(new File(filename)); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // only directories // fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); // only files // fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // both files and directories // pop up an "Open File" file chooser dialog fileChooser.showOpenDialog(frame); System.out.println("File to open: " + fileChooser.getSelectedFile()); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
This was an example on how to select file selection mode in file chooser.