Java Reference
In-Depth Information
•
addChoosableFileFilter(FileFilter filter)
: Filters the file list using the file filter you sup-
ply as the argument.
•
setSelectedFile(File file)
:Sets
file
as the file preselected when the dialog opens.
Contents of the File List
You can set a file chooser dialog to display files, directories, or both. You determine what is displayed in a
dialog by calling the
setFileSelectionMode()
method. The argument must be one of the
int
constants
FILES_ONLY
,
DIRECTORIES_ONLY
, and
FILES_AND_DIRECTORIES
that are defined as static members of the
JFileChooser
class.
FILES_ONLY
is the default selection mode. The
getFileSelectionMode()
method re-
turns the current selection mode.
By default a user can select only one file or directory, but you can allow multiple selections to be
made from the list in the file dialog if you call the
setMultiSelectionEnabled()
method for your
JFileChooser
object with the argument
true
.
Preselecting a File
If you want the dialog to have a particular file selected when it opens, you pass a
java.io.File
object to the
setSelectedFile()
method for the
JFileChooser
object. This will preselect the file in the file list if the
file already exists, and inserts the file name in the file name field if it doesn't. You can create a
File
object
from a
Path
object by calling its
toFile()
method. If you have enabled multiple selections in the dialog,
you can pass an array of
File
objects to the
setSelectedFiles()
method to have several files preselected
when the dialog opens.
Updating the File List
The file list is created when you create the
JFileChooser
object, but naturally files may be added or deleted
over time, and when this occurs you need to reconstruct the file list in the dialog object. Calling the
res-
canCurrentDirectory()
method before you display the dialog does this for you. You can change the cur-
rent directory at any time by passing a
File
object specifying the directory you want to make current to the
setCurrentDirectory()
method.
Filtering the File List
You can supply a file filter for the sketch files. The default file filter in a
JFileChooser
object accepts any
file or directory, but you can add one or more filters of your own to select a subset of the files in the current
directory. A file filter object is of a type that has the
javax.swing.filechooser.FileFilter
class as a
superclass. The
FileFilter
class declares two methods, both of which are abstract, so your file filter class
must implement them:
• The
accept(File file)
method: Returns
true
if the file represented by
file
is accepted by the
file filter and returns
false
otherwise.
• The
getDescription()
method: Returns a
String
object that describes the filter — “Sketch
files," for example.
The
JFileChooser
class works with
File
objects rather than
Path
objects, so the filter has to work with
File
objects, too.