Creating File Chooser Dialog by Using JFileChooser

File chooser dialog box is used for navigating the file system. With file chooser you can choose either file or directory from file or directory list. In order to display file chooser you use JFileChooser API.  In addition, you can also display file chooser by adding JFileChoose instance to a container.

The code snippet to bring up the file chooser dialog as follows:

  1. First you create a JFileChooser instance.
  2. Then you call method showOpenDialog() and pass the parent container to it.  Note that the parent container affects the position of the file chooser dialog and the frame that the dialog depends on.

By default, file chooser shows all files and directories in user’s default directory. You can use methodsetCurrentDirectory() to initalize the init directory for the file chooser.

You can use showSaveDialog() method to show save dialog beside showOpenDialog() method. Both of these methods return an integer to indicate whether user choosed a file or not. Normally you check the return value equals to a constant APPROVE_OPTION to make sure that user has chosen files or directories.

In order to get the selected files or directories you use method getSelectedFile() or getSelectedFiles().These methods return an instance of File or File[]

To limit user to choose only files or directories you can call method setFileSelectionMode(). There are three modes you can use:

  1. Files only (JFileChooser.FILES_ONLY).
  2. Directories only (JFileChooser.DIRECTORIES_ONLY).
  3. Files and Directories (JFileChooser.FILES_AND_DIRECTORIES).

You can allow user to choose multiple files or directories by enabling multiple selection using methodsetMultiSelectionEnabled().

Here are the constructors of JFileChooser:

ConstructorsDescription
JFileChooser()Creates JFileChooser instance using user’s default directory.
JFileChooser(File currentDirectory)Creates JFileChooser instance using a given directory.
JFileChooser(File currentDirectory, FileSystemView fsv)Creates JFileChooser instance using a specific directory and uses given FileSystemView.
JFileChooser(FileSystemView fsv)Creates JFileChooser instanceusing a givenFileSystemView.
JFileChooser(String currentDirectoryPath)Creates JFileChooser instanceusing a given path.
JFileChooser(String currentDirectoryPath, FileSystemView fsv)Creates JFileChooser instance using a given directory path and FileSystemView.

Here is the screenshot of JFileChooser demo application:

JFileChooser

JFileChooser

JFileChooser

  • Was this tutorial helpful ?
  • YesNo