Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 24: Using AWT Controls, Layout Managers, and Menus 747


FileDialog


Java provides a built-in dialog box that lets the user specify a file. To create a file dialog box,
instantiate an object of typeFileDialog. This causes a file dialog box to be displayed. Usually,
this is the standard file dialog box provided by the operating system. Here are three
FileDialogconstructors:

FileDialog(Frameparent)
FileDialog(Frameparent, StringboxName)
FileDialog(Frameparent, StringboxName, inthow)

Here,parentis the owner of the dialog box. TheboxNameparameter specifies the name
displayed in the box’s title bar. IfboxNameis omitted, the title of the dialog box is empty. If
howisFileDialog.LOAD, then the box is selecting a file for reading. IfhowisFileDialog.SAVE,
the box is selecting a file for writing. Ifhowis omitted, the box is selecting a file for reading.
FileDialogprovides methods that allow you to determine the name of the file and its
path as selected by the user. Here are two examples:

String getDirectory( )
String getFile( )

These methods return the directory and the filename, respectively.
The following program activates the standard file dialog box:

/* Demonstrate File Dialog box.

This is an application, not an applet.
*/
import java.awt.*;
import java.awt.event.*;

// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);

// remove the window when closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

}
}

// Demonstrate FileDialog.
class FileDialogDemo {
public static void main(String args[]) {
// create a frame that owns the dialog
Frame f = new SampleFrame("File Dialog Demo");
f.setVisible(true);
Free download pdf