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.