14. Files and Streams: Input/Output Techniques

14.6. From the Java Library

javax.swing.JFileChooser

 

 

THE javax.swing.JFileChooser class is useful for dealing with files and directories in a GUI environment. You are probably already familiar with JFileChoosers, although you may not have known them by that name. A JFileChooser provides a dialog box that enables the user to select a file and a directory when opening or saving a file. Figure 11.30 shows an example.

A JFileChooser is designed primarily to be used in conjunction with menu-based programs. The JFileChooser class (Fig. 11.29) contains methods that support the Open File and Save As options which often ap- pear in GUI applications either in a menu or attached to buttons. In this section we provide the basics for using a JFileChooser. Options for opening a file or saving a file can be added to the kind of GUI applications that we encountered earlier in the text by using buttons. In Chapter 13, we will discuss the use of JMenus which will provide a more natural means of using the JFileChooser dialogs.

A JFileChooser is not itself the dialog window, but rather the object that manages the dialog. After creating a JFileChooser instance, its showOpenDialog() or showSaveDialog() methods are used to open a dialog window. Note that these methods require a Component parame- ter, usually a JFrame or a JApplet. Thus, JFileChoosers can be used only in GUI applications and applets.

To illustrate how to use a JFileChooser, let’s consider the case where the user has selected an Open File menu item or clicked a button labeled Open File. In this case, executing the following code will cause an “Open File” dialog to appear:

,,


java.sun.com/j2se/1.5.0/docs/api/

 

 

 

 

 

 

 

 

 

Figure11.29:The javax.swing.JFileChooser class.

 

 

 

 

 

 

J

We begin by creating a JFileChooser and then telling it to showOpen- Opening a file

Dialog(). If we were saving a file rather than opening one, we would tell it to showSaveDialog(). In either case, a dialog window will pop up on the screen. The dialog assists the user in navigating through the file system and selecting a file (Fig. 11.30).

The dialog contains two buttons, one labeled Open and the other la- beled Cancel. If the user selects a file, that choice will correspond to APPROVE OPTION. If the user cancels the dialog, that will correspond to CANCEL OPTION. After opening a dialog, the code should check which option resulted. In this case, if the user opened a file, the code gets a

 

Figure 11.30: The Open File dialog window.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

modifying WordGuess

 

 

 

 

 

 

 

 

 

 

 

New instance variables


 

reference to the file and then simply uses that to print the file’s path name to a text area named display. In an actual application, code would be inserted at that spot which uses the file reference to read data from the file.