The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
< Day Day Up > |
How to Use File Choosers
File choosers provide a GUI for navigating the file system and then either choosing a file or directory from a list or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API [41] to show a modal dialog that contains it. Another way to present a file chooser is to add an instance of JFileChooser to a container. [41] JFileChooser API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html.
Note: [42] To run JWSFileChooserDemo using Java Web Start, click the JWSFileChooserDemo link on the RunExamples/ components .html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#JWSFileChooserDemo .
The rest of this section discusses how to use the JFileChooser API. A JFileChooser object only presents the GUI for choosing files. Your program is responsible for doing something with the chosen file, such as opening or saving it. Refer to The Java Tutorial trail "I/O: Reading and Writing (but no 'rithmetic)" online for information on how to read and write files. [43] [43] The "I/O" trail is available in the The Java Tutorial on this book's CD and online at: http://java.sun.com/docs/books/tutorial/essential/io/index.html. Example One: FileChooserDemo
The JFileChooser API makes it easy to bring up open and save dialogs. The look and feel determines what these standard dialogs look like and how they differ . In the Java look and feel (see Figure 15), the save dialog looks the same as the open dialog except for the title on the dialog's window and the text on the button that approves the operation (see Figure 16). Figure 15. The Java look and feel's standard open dialog.
Figure 16. The FileChooserDemo , an application that brings up an open dialog and a save dialog.
Try This:
Bringing up a standard open dialog requires only two lines of code: //Create a file chooser final JFileChooser fc = new JFileChooser(); .. //In response to a button click: int returnVal = fc.showOpenDialog(aComponent); The argument to the showOpenDialog method specifies the parent component for the dialog. The parent component affects the position of the dialog and the frame that it depends on. For example, the Java look and feel places the dialog directly over the parent component. If the parent component is in a frame, the dialog is dependent on that frame, disappearing when the frame is iconified and reappearing when it's deiconified. By default, a file chooser that hasn't been shown previously displays all files in the user 's home directory. You can specify the file chooser's initial directory using one of JFile-Chooser 's other constructors, or you can set the directory with the setCurrentDirectory method. The call to showOpenDialog appears in the actionPerformed method of the Open a File... button's action listener: public void actionPerformed(ActionEvent e) { //Handle open button action. if (e.getSource() == openButton) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would open the file. log.append("Opening: " + file.getName() + "." + newline); } else { log.append("Open command canceled by user." + newline); } } ... } The show Xxx Dialog methods return an integer that indicates whether the user selected a file. Depending on how you use a file chooser, it's often sufficient to check whether the return value is APPROVE_OPTION and to do nothing for any other value. To get the chosen file, call getSelectedFile on the file chooser. This method returns an instance of File . [45] [45] File API documentation is on the CD and online at: http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html. The example gets the name of the file and uses it in the log message. You can call other methods on the File object, such as getPath , isDirectory , or exists , to get information about the file. You can also call other methods, such as delete and rename , 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 Java platform. See The Java Tutorial trail "I/O: Reading and Writing (but no 'rithmetic)" for information on using readers and writers to read and write data to and from the file system. [46] [46] The "I/O" trail is available in the The Java Tutorial on this book's CD and online at: http://java.sun.com/docs/books/tutorial/essential/io/index.html. The example program uses the same instance of JFileChooser to display a standard save dialog. This time the program calls showSaveDialog : int returnVal = fc.showSaveDialog(FileChooserDemo.this); By using the same file chooser instance to display its open and save dialogs, the program reaps these benefits:
The example program has commented-out lines of code that let you change the file selection mode. For example, the following line of code makes the file chooser select only directories, and not files: fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); Another possible selection mode is FILES_AND_DIRECTORIES . The default is FILES_ONLY . Figure 17 shows an open dialog with the file-selection mode set to DIRECTORIES_ONLY . Figure 17. An open dialog in DIRECTORIES_ONLY mode in the Java look and feel.
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. Example Two: FileChooserDemo2
Figure 18. The FileChooserDemo2 application permits the preview of image files.
The figure shows that this file chooser has been customized for a special task ( Attach ), provides a user-choosable file filter ( Just Images ), uses a special file view for image files (PNG/GIF/JPEG symbols), and has an accessory component that displays a thumbnail sketch of the currently selected image file. Using a File Chooser for a Custom Task
As you've seen, JFileChooser provides the showOpenDialog method for displaying an open dialog and the showSaveDialog method for displaying a save dialog. The class has another method, showDialog , for displaying a file chooser for a custom task in a dialog. In the Java look and feel, the only difference between this dialog and the other file chooser dialogs is the title on the dialog window and the label on the Approve button. The following is the code from FileChooserDemo2 that brings up the file chooser dialog for the Attach task: JFileChooser fc = new JFileChooser(); int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach"); The first argument to the showDialog method is the parent component for the dialog. The second argument is a String that provides both the title for the dialog window and the label for the Approve 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, except hidden files, 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's accept 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. For example, an application-controlled filter sees only those files accepted by the built-in filtering. 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 a period (.) on UNIX systems. By default, hidden files are not shown. Call setFileHiding-Enabled(false) to show hidden files. Application-Controlled Filtering
The application determines which files are shown. Create a custom subclass of FileFilter , [48] instantiate it, and use the instance as an argument to setFileFilter . The file chooser shows only those files that the filter accepts. [48] FileFilter API documentation is on the CD and online at: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileFilter.html. User-Choosable Filtering
The file chooser GUI provides a list of filters that the user can choose from. When the user selects a filter, the file chooser shows only those files that the filter accepts. FileChooserDemo2 adds a custom file filter to the list of user-choosable filters: fc.addChoosableFileFilter(new ImageFilter()); By default, the list of user-choosable filters includes the Accept All filter, which lets the user see all nonhidden files. This example uses the following code to disable the Accept All filter: fc.setAcceptAllFileFilterUsed(false);
public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.tiff) extension.equals(Utils.tif) extension.equals(Utils.gif) extension.equals(Utils.jpeg) extension.equals(Utils.jpg) extension.equals(Utils.png)) { return true; } else { return false; } } return false; } By accepting all directories, this filter allows the user to navigate 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 class Utils { public final static String jpeg = "jpeg"; public final static String jpg = "jpg"; public final static String gif = "gif"; public final static String tiff = "tiff"; public final static String tif = "tif"; public final static String png = "png"; /* * Get the extension of a file. */ public static 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; } } Customizing the File View
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 this file view by creating a custom subclass of FileView [51] and using an instance of the class as an argument to setFileView . The example uses an instance of a custom class, implemented in ImageFileView.java , [52] as the file chooser's file view. [51] FileView API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/filechooser/FileView.html. [52] ImageFileView.java is included on the CD and is available online. You can find it here: JavaTutorial/uiswing/components/example-1dot4/ImageFileView.java . 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 in FileView as follows : String getTypeDescription(File f)
Returns a description of the file type. This is not yet used by any look and feel. Here's ImageFileView 's implementation of this method: public String getTypeDescription(File f) { String extension = Utils.getExtension(f); String type = null; if (extension != null) { if (extension.equals(Utils.jpeg) extension.equals(Utils.jpg)) { type = "JPEG Image"; } else if (extension.equals(Utils.gif)){ type = "GIF Image"; } else if (extension.equals(Utils.tiff) extension.equals(Utils.tif)) { type = "TIFF Image"; } else if (extension.equals(Utils.png)){ type = "PNG Image"; } } return type; } Icon getIcon(File f)
Returns an icon representing the file or its type. Here's ImageFileView 's implementation of this method: public Icon getIcon(File f) { String extension = Utils.getExtension(f); Icon icon = null; if (extension != null) { if (extension.equals(Utils.jpeg) extension.equals(Utils.jpg)) { icon = jpgIcon; } else if (extension.equals(Utils.gif)) { icon = gifIcon; } else if (extension.equals(Utils.tiff) extension.equals(Utils.tif)) { icon = tiffIcon; } else if (extension.equals(Utils.png)) { icon = pngIcon; } } return icon; } String getName(File f)
Returns the name of the file. Most implementations of this method return null to indicate that the look and feel should figure it out. Another common implementation returns f.getName() . String getDescription(File f)
Returns a description of the file. This isn't used by any look and feel yet. 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. Most implementations 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 that represents a compound document. The isTraversable method should never return true for a nondirectory. Providing an Accessory Component
The customized file chooser in FileChooserDemo2 has an accessory component. If the currently selected item is a PNG, 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 itsay, check boxes that toggle some features.
fc.setAccessory(new ImagePreview(fc)); Any object that inherits from JComponent can be an accessory component. The component should 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. 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 of the code related to the accessory component together in one class. Here's the example's implementation of the propertyChange method, which is called when a property change event is fired : //where member variables are declared File file = null; .. public void propertyChange(PropertyChangeEvent e) { boolean update = false; String prop = e.getPropertyName(); //If the directory changed, don't show an image. if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) { file = null; update = true; //If a file became selected, find out which one. } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY. equals(prop)){ file = (File) e.getNewValue(); update = true; } //Update the preview accordingly. if (update) { thumbnail = null; if (isShowing()) { loadImage(); repaint(); } } } If SELECTED_FILE_CHANGED_PROPERTY is the property that changed, this method gets a File object from the file chooser. The loadImage and repaint methods use the File object to load the image and repaint the accessory component. The File Chooser API
The API for using file choosers falls into four categories, as shown in Tables 21 through 24. You should also refer to the JFileChooser API documentation. [54] [54] JFileChooser API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html. Table 21. Creating and Showing the File Chooser
Table 22. Selecting Files and Directories
Table 23. Navigating the File Chooser's List
Table 24. Customizing the File Chooser
Examples That Use File Choosers
The following table shows examples that use JFileChooser and where those examples are described.
|
< Day Day Up > |