Using Swing Components |
TheJFileChooser
class provides a UI for choosing a file from a list. A file chooser is a component that you can place anywhere within your program's GUI. However, programs typically display file choosers in modal dialogs because file operations can be sensitive to changes within the program. TheJFileChooser
class makes it easy to bring up a modal dialog that contains a file chooser.File choosers are most commonly used for two purposes:
- to present a list of files that can be opened by the application.
- to allow the user to select or enter the name of a file to be saved.
Note that the file chooser doesn't itself open or save files. It presents a GUI for choosing a file from a list. The program is responsible for then doing something with the file, such as opening or saving it.
Because most programmers want an open file chooser or a save file chooser, the
When you click the Open button the program brings up an open file chooser. When you click the Save button the program brings up a save file chooser. Here's a picture of the the open file chooser: In the Java Look and Feel, the only difference between the open file chooser and the save file chooser is the title on the dialog window and the label on the "accept" button.JFileChooser
class provides convenience methods for displaying these types of file choosers in a dialog:showOpenDialog
andshowSaveDialog
. Our first example,FileChooserDemo.java
, illustrates the use of both:You need only two lines of code to create and show an open file chooser:
By default, a file chooser that hasn't been shown before displays all files in the user's home directory. You can specify the file chooser's initial directory using one of//where member variables are declared private JFileChooser fc = new JFileChooser(); ... //in the ActionPerformed method of the Open button's action listener int returnVal = fc.showOpenDialog(FileChooserDemo.this);JFileChooser
's other constructors, or you can set the directory with thesetCurrentDirectory
method.The example program uses the same instance of
JFileChooser
to display the save file chooser. Here's theactionPerformed
method for the Save button's listener:By using the same file chooser for its open and save file chooser, the program reaps these benefits:public void actionPerformed(ActionEvent e) { int returnVal = fc.showSaveDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); log.append("Saving: " + file.getName() + "." + newline); } else { log.append("Save command cancelled by user." + newline); } }As you can see from the previous code snippets, the
- The chooser remembers the current directory between uses so the open and save dialogs automatically share the same current directory.
- You have to customize only one file chooser, and your customizations apply to both the open and save versions of it.
showOpenDialog
andshowSaveDialog
methods return an integer that indicates whether the user selected a file. You can use the return value to determine whether to perform the required operation.If the user chooses a file, the example calls
getSelectedFile
on the file chooser to get an instance ofFile
, which represents the chosen file. The example gets the name of the file and uses it in the log message. You can call other methods on theFile
object, such asgetPath
,isDirectory
, orexists
to get information about the file. You can also call other methods such asdelete
andrename
to change the file in some way. Of course, you might also want to open or save the file using one of the reader or writer classes provided by the JDK. See Reading and Writing for information about using readers and writers to read and write data to the file system.If you want to create a file chooser for a task other than opening or saving, or if you want to customize the file chooser, keep reading. These topics about the file chooser follow:
- FileChooserDemo: Take 2
- Using a File Chooser for a Custom Task
- Filtering the List of Files
- Customizing the File View
- Providing an Accessory Component
- The File Chooser API
- Examples that Use File Choosers
FileChooserDemo: Take 2
Now let's look atFileChooserDemo2.java
, a modified version of the previous demo program that uses more of theJFileChooser
API. This example uses a file chooser that has been customized in several ways. Like the original example, the user invokes a file chooser with the push of a button. Here's a picture of the file chooser: [PENDING: add callouts to figure to point out file view, accessory, user-choosable filter, etc]You need these source files to run this example:
FileChooserDemo2.java
,ImageFilter.java
,ImageFileView.java
, andImagePreview.java
.As the figure shows, this file chooser has been customized for a special task (attaching), provides a user-choosable file filter, uses a special file view for image files, and has an accessory component that displays a thumbnail sketch of the currently selected image file.
The remainder of this section shows you the code that creates and customizes this file chooser.
Using a File Chooser for a Custom Task
As you've seen,JFileChooser
providesshowOpenDialog
for displaying an open file chooser andshowOpenDialog
for displaying a save file chooser. In the Java Look and Feel, the only difference between the two choosers is the title on the dialog window and the label on the "accept" button.The class has another method,
showDialog
, for displaying a file chooser for a custom task in a dialog. Again, the only difference between this file chooser and the others is the title on the dialog window and the label on the "accept" button. Here's the code fromFileChooserDemo2
that brings up the file chooser dialog for the Attach task.The first argument to the//where member variables are declared private JFileChooser fc = new JFileChooser(); ... //in the ActionPerformed method of the Attach button's action listener int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach");showDialog
method is the parent component for the dialog. The second argument is aString
that provides both the title for the dialog window and the label for the accept button.Once again, the file chooser doesn't do anything with the selected file. The program is responsible for implementing the custom task for which the file chooser was created.
Filtering the List of Files
By default, a file chooser displays all of the files and directories that it detects. A program can apply one or more file filters to a file chooser so that the chooser shows only some files. The file chooser calls the filter'saccept
method for each file to determine whether it should be displayed. A file filter accepts or rejects a file based on some criteria such as file type, size, ownership, and so on. Filters affect the list of files displayed by the file chooser. The user can enter the name of any file even if it's not displayed.
JFileChooser
supports three different kinds of filtering. The filters are checked in the order listed here. So a filter of the second type can filter only those files accepted by the first and so on.
- Built-in filtering
- Filtering is set up through specific method calls on a file chooser. Currently the only built-in filter available is for hidden files, such as those that begin with period (.) on UNIX systems. By default, hidden files are not shown. Call
setFileHidingEnabled(false)
to show hidden files.- Application-controlled filtering
- The application determines which files are shown. Create a custom subclass of
FileFilter
, instantiate it, and use the instance as an argument tosetFileFilter
. The file chooser shows only those files that the filter accepts.- User-choosable filtering
- The file chooser GUI provides a list of filters that the user can choose from. When the user chooses a filter, the file chooser shows only those file accepted by that filter.
FileChooserDemo2
adds a custom file filter to its file chooser's list of user-choosable filters:The custom file filter is implemented infc.addChoosableFileFilter(new ImageFilter());ImageFilter.java
, as a subclass ofFileFilter
. TheImageFilter
class implements thegetDescription
method to return a string to put in the list of user-choosable filters. As the following code shows,ImageFilter
implements theaccept
method to accept all directories and any file that has a ".jpg", ".jpeg", ".gif", ".tif", or ".tiff" filename extension.By accepting all directories, this filter allows the user to navigate around the file system. If the bold lines were omitted from this method, the user would be limited to the directory with which the chooser was initialized.public boolean accept(File f) { if (f.isDirectory()) { return true; } String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { String extension = s.substring(i+1).toLowerCase(); if (tiff.equals(extension) || tif.equals(extension) || gif.equals(extension) || jpeg.equals(extension) || jpg.equals(extension)) { return true; } else { return false; } } return false; }Customizing the File View
File choosers present a list of files to choose from. In the Java Look and Feel, the chooser's list shows each file's name and displays a small icon that represents whether the file is a true file or a directory. You can customize the list's file view by creating a custom subclass ofFileView
and using an instance of the class as an argument tosetFileView
. The example uses an instance ofImageFileView
as the file chooser's file view:fc.setFileView(new ImageFileView());ImageFileView
shows a different icon for each type of image accepted by the image filter described previously.The
ImageFileView
class overrides the five abstract methods defined inFileView
as follows. Note that some of these methods callgetExtension
, which is a private method toImageFileView
.The
String getTypeDescription(File f)
- Returns a description of the file type. This is not yet used by any current Look and Feel. The intent is to provide information about the file's type. Here is
ImageFileView
's implementation of this method:public String getTypeDescription(File f) { String extension = getExtension(f); String type = null; if (extension != null) { if (extension.equals("jpeg")) { type = "JPEG Image"; } else if (extension.equals("gif")){ type = "GIF Image"; } else if (extension.equals("tiff")) { type = "TIFF Image"; } } return type; }Icon getIcon(File f)
- Returns an icon representing the file or its type. Here is
ImageFileView
's implementation of this method:public Icon getIcon(File f) { String extension = getExtension(f); Icon icon = null; if (extension != null) { if (extension.equals("jpeg")) { icon = jpgIcon; } else if (extension.equals("gif")) { icon = gifIcon; } else if (extension.equals("tiff")) { icon = tiffIcon; } } return icon; }String getName(File f)
- Returns the name of the file. Most implementations of this method should return
null
to indicate that the Look and Feel should figure it out. Another common implementation returnsf.getName()
.
String getDescription(File f)
- Returns a description of the file. This is not yet used by any current Look and Feel. The intent is to describe individual files more specifically. A common implementation of this method returns
null
to indicate that the Look and Feel should figure it out.
Boolean isTraversable(File f)
- Returns whether a directory is traversable or not. Most implementations of this method should return
null
to indicate that the Look and Feel should figure it out. Some applications might want to prevent users from descending into a certain type of directory because it represents a compound document. An implementor ofisTraversable
should never returntrue
for a non-directory.ImageFileView
implementation of both thegetTypeDescription
andgetIcon
methods uses a custom method calledgetExtension
implemented as follows:private String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i+1).toLowerCase(); } return ext; }Providing an Accessory Component
The customized file chooser inFileChooserDemo2
has an accessory component. If the currently selected item is a JPEG, TIFF, or GIF image, the accessory component displays a thumbnail sketch of the image. Otherwise, the accessory component is empty. Aside from a previewer, probably the most common use for the accessory component is a panel with more controls on it (say, checkboxes that toggle some features).The example calls the
setAccessory
method to establish an instance ofImagePreview
as the chooser's accessory component:Any object that inherits fromfc.setAccessory(new ImagePreview(fc));JComponent
can be an accessory component. The component should implement eitherpaint
orpaintComponent
and have a preferred size that looks good in the file chooser.The file chooser fires a property change event when the user selects an item in the list. So, a program with an accessory component must register to receive these events to update the accessory component whenever the selection changes. In the example, the
ImagePreview
object itself registers for these events. This keeps all the code related to the accessory component together in one class.Here is the example's implementation of the
propertyChange
method, which is the method called when a property change event is fired:If//where member variables are declared File f = null; ... public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) { f = (File) e.getNewValue(); if (isShowing()) { loadImage(); repaint(); } } }SELECTED_FILE_CHANGED_PROPERTY
is the property that changed, this method gets aFile
object from the file chooser. TheloadImage
andrepaint
methods use theFile
to load the image and repaint the accessory component.The File Chooser API
The API for using file choosers falls into these categories:
- Creating and Showing a File Chooser
- Navigating the File Chooser's List
- Customizing the File Chooser
- Selecting Files and Directories
Creating and Showing a File Chooser Method Purpose JFileChooser()
JFileChooser(File)
JFileChooser(String)Create a file chooser instance. The File
andString
arguments, when present, provide the initial directory.int showOpenDialog(Component)
int showSaveDialog(Component)
int showDialog(Component, String)Show a modal dialog containing the file chooser.
Navigating the File Chooser's List Method Purpose void ensureFileIsVisible(File)
Force the indicated file to be visible in the file chooser's list. void setCurrentDirectory(File)
File getCurrentDirectorySet or get the directory whose files are displayed in the file chooser's list. void changeToParentDirectory()
Change the list to display the current directory's parent. void rescanCurrentDirectory()
Check the file system and update the chooser's list.
Customizing the File Chooser Method Purpose JComponent getAccessory()
void setAccessory(JComponent)Set or get the file chooser's accessory component. void setFileFilter(FileFilter)
FileFilter getFileFilter()Set or get the file chooser's primary file filter. void setFileView(FileView)
FileView getFileView()Set or get the chooser's file view. FileFilter[] getChoosableFileFilters()
void setChoosableFileFilters(FileFilter[])
void addChoosableFileFilter(FileFilter)
boolean removeChoosableFileFilter(FileFilter)
void resetChoosable(FileFilter)
FileFilter getAcceptAllFileFilter()Set, get, or modify the list of user-choosable file filters. void setFileHidingEnabled(boolean)
boolean isFileHidingEnabled()Set or get whether hidden files are displayed.
Selecting Files and Directories Method Purpose void setFileSelectionMode(int)
int getFileSelectionMode()
boolean isDirectorySelectionEnabled()
boolean isFileSelectionEnabled()Set the file selection mode. Acceptable values are FILES_ONLY
,DIRECTORIES_ONLY
, andFILES_AND_DIRECTORIES
.void setMultiSelectionEnabled(boolean)
boolean isMultiSelectionEnabled()Set or get whether multiple files can be selected at once. void setSelectedFile(File)
File getSelectedFile()Set or get the currently selected file. void setSelectedFiles(File[])
File[] getSelectedFiles()Set or get the currently selected files. Examples that Use File Choosers
This table shows the examples that useJFileChooser
and where those examples are described.
Example Where Described Notes FileChooserDemo.java
This page Invokes an open file chooser and a save file chooser. FileChooserDemo2.java
This page Uses a file chooser with custom filtering, a custom file view, and an accessory component.
Using Swing Components |