Page 663 - Introduction to Programming with Java: A Problem Solving Approach
P. 663
15.10 GUI Track: The JFileChooser Class (Optional) 629 15.10 GUI Track: The JFileChooser Class (Optional)
In the previous section’s FileSizes program, we displayed the filenames and file sizes for all the files in the current directory. But suppose what you’re looking for is in another directory. Wouldn’t it be nice to display filenames and file sizes for any directory, not just the current directory? This section presents a program that does just that. It uses a GUI format to display filenames and file sizes for a user-specified directory. The program gets the user’s directory selection with the help of the JFileChooser dialog box. Before looking at the program, let’s consider the JFileChooser dialog box defined in the Java API.
User Interface
A file-chooser dialog box allows the user to select a file or a directory from a graphical, interactive direc- tory structure. File choosers are ubiquitous in modern software. For example, a word processor employs a file chooser whenever the user selects Open from the File menu. Figure 15.14 shows how a user selects a file with the help of a JFileChooser dialog box.
JFileChooser Usage
The JFileChooser class is defined in the javax.swing package, so you must import that package to access this class. To create a JFileChooser dialog box, call the JFileChooser constructor like this:
Apago PDF Enhancer
JFileChooser chooser = new JFileChooser(<current-directory>);
The current-directory argument specifies the name of the directory that initially appears at the top of the file-chooser dialog box. That’s the file chooser’s current directory. This statement shows how we created Figure 15.14’s file chooser:
JFileChooser chooser = new JFileChooser(".");
As mentioned previously, the "." argument represents the computer’s current directory. Be aware that the file chooser’s current directory and the computer’s current directory aren’t always the same. If you called the JFileChooser constructor with a "C:/spreadsheets" argument, file chooser’s current directory would be C:/spreadsheets, but the computer’s current directory would be unaffected.
The JFileChooser class has many methods. We’ll look at just three of them—the setFileSelectionMode, showOpenDialog, and getSelectedFile methods. Here are their API headings and descriptions:
public void setFileSelectionMode(int mode)
Specifies the type of file the user can choose—a file, a directory, or either one.
public int showOpenDialog(null)
Displays a file-chooser dialog box. Returns a named constant, which indicates whether the user selected Open or Cancel.
public File getSelectedFile()
Returns the selected file or directory.