File Dialogs  «Prev  Next»


Lesson 3FileDialog Creation
ObjectiveCreate the FileDialog using Constructor

Create FileDialog using Constructor

Familiarize yourself with use of FileDialog Constructor

You create a FileDialog object with this constructor:
public FileDialog(Frame parent, String title, int mode)

The Frame is the parent of this file dialog box. This will normally be the main window of the application, the applet's frame, or the frontmost window of the application. Or you can just create a new Frame.
The title argument is simply the title for the file dialog box, normally something like "Please choose the file to open: "
The mode argument is one of the two mnemonic constants FileDialog.LOAD or FileDialog.SAVE. Use FileDialog.LOAD if you want the user to choose a file to open. Use FileDialog.SAVE if you want the user to choose a file to save the data into.
A typical use of this constructor might look like this:

Legacy AWT API

FileDialog fd = new FileDialog(new Frame(),
 "Please choose the file to open:", FileDialog.LOAD);

AWT Application that allows you to select files from your Desktop

The following program activates the standard file dialog box:
The first class named FileDialogDemo contains the main method and is the driver for the application.
package com.java.io;

import java.awt.*;
import java.awt.event.*;

class FileDialogDemo{
 public static void main(String args[]) {
   Frame f = new SampleFrame("File Dialog Demo");
   f.setVisible(true);
   f.setSize(100,100);
   FileDialog fd = new FileDialog(f, "File Dialog");
   fd.setVisible(true);			
 }
}
The following class SampleFrame contains the AWT components to select files on your machine after the program has been executed.
import java.awt.*;
import java.awt.event.*;

public 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);
	}
  });
 }
}