Using Dialog Boxes in Java


Java provides a built-in class, FileDialog, to allow the user to select files for saving or loading. The constructors for FileDialog include
    FileDialog(Frame, String) 
    FileDialog(Frame, String, int)
The constructor creates a file dialog window associated with the specified frame and with the specified title for loading or saving a file. The optional int argument is FileDialog.LOAD or FileDialog.SAVE. If omitted the default is FileDialog.LOAD. The following sample code shows how a FileDialog can be used in a program to get a file name to be read from.
	String fileName;
	do{
		dialog = new FileDialog(myFrame,"Load a schedule file");
		dialog.show();
		fileName = dialog.getFile();
	}	while (fileName == null);
This code attaches a dialog box to myFrame. When executed, the code creates and shows the dialog. The dialog.getFile() command either returns a string representing the file name to be loaded or null (if the cancel button is clicked from the dialog box). Thus the loop continues creating and displaying the dialog box until a file is selected.

The programmer now must write commands to open and read from the file.