File Dialogs  «Prev  Next»


Lesson 4Specify Start Directory
Objective Point at a default directory or file

Point at Default Directory File

Examine the use of the setDirectory() method.

Many times you will want some control over the file dialog box. You may want to specify that it should start looking in a particular directory. To start the file dialog box at a default directory, call the FileDialog class's setDirectory(String dir) method where dir is the path to the directory.
Here is an example of using the setDirectory method:

fd.setDirectory("/usr/tmp");


To specify that the file dialog should appear with a particular directory opened or a particular file in that directory selected, you can invoke the setDirectory() and setFile() methods:
public synchronized void setDirectory(String directory)
public synchronized void setFile(String file)

For example:
fd.setDirectory("/etc");
fd.setFile("passwd");

You make the file dialog visible by invoking the file dialog's show() method, just like any other window:
fd.show();

As soon as the file dialog becomes visible, the calling thread stops and waits for the user to choose a file. The operating system takes over and handles user interaction until the user chooses a file or presses the Cancel button. At this point, the file dialog disappears from the screen, and normal program execution resumes.

Once the dialog has been dismissed, you can find out which file the user chose by using the file dialog's getDirectory() and getFile() methods:
public String getFile()
public String getDirectory()

For example:
FileDialog fd = new FileDialog(new Frame(), "Please choose a file:",
FileDialog.LOAD);
fd.setVisible(true);
File f = new File(fd.getDirectory(), fd.getFile());

If the user cancels the file dialog without selecting a file, getFile() and getDirectory() return null. You should be ready to handle this, or you'll bump into a NullPointerException in short order.