import java.awt.*;
import java.awt.event.*;
import java.io.*;

/** Uses a FileDialog to choose the file to display. 
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  http://www.corewebprogramming.com/.
 *  &copy; 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class DisplayFile extends CloseableFrame 
                         implements ActionListener {
                                
  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");
    loadButton.addActionListener(this);
    Panel buttonPanel = new Panel();
    buttonPanel.add(loadButton);
    add(buttonPanel, BorderLayout.SOUTH);
    fileArea = new TextArea();
    add("Center", fileArea);
    loader = new FileDialog(this, "Browse", FileDialog.LOAD);
    // Default file extension: .java.
    loader.setFile("*.java");
    setSize(350, 450);
    setVisible(true);
  }

  /** When the button is clicked, a file dialog is opened. When 
   * the file dialog is closed, load the file it referenced.
   */
  
  public void actionPerformed(ActionEvent event) {
      loader.show();
      displayFile(loader.getFile());
  }

  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);
      String fileContentsString = new String(fileContents);
      fileArea.setText(fileContentsString);
    } catch(IOException ioe) {
      fileArea.setText("IOError: " + ioe);
    }
  }
}