12.7.3 File dialogs



Some operating systems have a number of special built-in dialog boxes to handle the selection of things such as fonts, colors, printers, and the like. Virtually all graphical operating systems support the opening and saving of files, however, and so Java's FileDialog encapsulates these for easy use. This, of course, makes no sense at all to use from an applet since an applet can neither read nor write files on the local disk. (This will change for trusted applets in newer browsers.)

The following application exercises the two forms of file dialogs, one for opening and one for saving. Most of the code should by now be familiar, and all the interesting activities happen in action( ) for the two different button clicks:

Case Study: FileDialogTest.java

For an "open file" dialog, you use the constructor that takes two arguments; the first is the parent window handle and the second is the title for the title bar of the FileDialog. The method setFile( ) provides an initial file name – presumably the native OS supports wildcards, so in this example all the .java files will initially be displayed. The setDirectory( ) method chooses the directory where the file selection will begin. (In general, the OS allows the user to change directories.)

The show( ) command doesn't return until the dialog is closed. The FileDialog object still exists, so you can read data from it. If you call getFile( ) and it returns null it means the user canceled out of the dialog. Both the file name and the results of getDirectory( ) are displayed in the TextFields.

The button for saving works the same way, except that it uses a different constructor for the FileDialog. This constructor takes three arguments and the third argument must be either FileDialog.SAVE or FileDialog.OPEN.


Next Page