import java.awt.*;
import java.io.*;

// This appears in Core Web Programming from
// Prentice Hall Publishers, and may be freely used
// or adapted. 1997 Marty Hall, hall@apl.jhu.edu.

/** Uses a FileDialog to choose the file to display. */

public class DisplayFile extends QuittableFrame {
  public static void main(String[] args) {
    new DisplayFile();
  }

  private Button loadButton;
  private TextArea fileArea;
  private FileDialog loader;

  public DisplayFile() {
    super("Using FileDialog");
    loadButton = new Button("Display File");
    Panel buttonPanel = new Panel();
    buttonPanel.add(loadButton);
    add("South", buttonPanel);
    fileArea = new TextArea();
    add("Center", fileArea);
    loader =
      new FileDialog(this, "Browse", FileDialog.LOAD);
    // Default file extension: .java
    loader.setFile("*.java");
    resize(500, 700);
    show();
  }

  /** When the button clicked, a file dialog is opened.
   *  When file dialog closed, load the file it
   *  referenced.
   */
  
  public boolean action(Event event, Object object) {
    if (event.target == loadButton) {
      loader.show();
      displayFile(loader.getFile());
      return(true);
    } else
      return(false);
  }

  public void displayFile(String filename) {
    try {
      File file = new File(filename);
      FileInputStream in = new FileInputStream(file);
      int fileLength = (int)file.length();
      byte[] fileContents = new byte[fileLength];
      in.read(fileContents);
      // Supply hiByte of 0 to turn byte[] into String
      String fileContentsString =
        new String(fileContents, 0);
      fileArea.setText(fileContentsString);
    } catch(IOException ioe) {
      fileArea.setText("IOError: " + ioe);
    }
  }
}
