import java.awt.*;
import java.net.*;

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

/** A class that compares the time to draw an image
 *  preloaded (getImage, prepareImage, and drawImage) vs.
 *  regularly. (getImage and drawImage).
 *  <P>
 *  The answer you get the regular way is dependent
 *  on the network speed and the size of the image, but
 *  if you assume you load the applet "long" (compared
 *  to the time the image loading requires) before
 *  pressing the button, the drawing time in the
 *  preloaded version depends only on the speed of
 *  the local machine.
 */

public class Preload extends Frame {
  public static void main(String[] args) {
    if (args.length == 0) {
      System.out.println("Must provide URL");
      System.exit(0);
    }
    if (args.length == 2 && args[1].equals("-preload"))
      new Preload(args[0], true);
    else
      new Preload(args[0], false);
  }

  private TextField timeField;
  private long start = 0;
  private boolean draw = false;
  private Image plate;

  public Preload(String imageFile, boolean preload) {
    super("Preloading Images");
    Panel buttonPanel = new Panel();
    buttonPanel.add(new Button("Display Image"));
    timeField = new TextField(25);
    timeField.setEditable(false);
    buttonPanel.add(timeField);
    add("South", buttonPanel);
    registerImage(imageFile, preload);
    resize(1000, 750);
    show();
  }

  /** If button has been clicked, draw image and
   *  show elapsed time. Otherwise do nothing.
   */
  public void paint(Graphics g) {
    if (draw) {
      g.drawImage(plate, 0, 0, this);
      showTime();
    }
  }

  /** No need to check which object caused this,
   *  since the button is the only possibility.
   */
  
  public boolean action(Event event, Object object) {
    draw = true;
    start = System.currentTimeMillis();
    repaint();
    return(true);
  }

  /** Honor requests to quit the window. */
  
  public boolean handleEvent(Event event) {
    if (event.id == Event.WINDOW_DESTROY)
      System.exit(0);
    return(super.handleEvent(event));
  }
  
  // Do getImage, optionally starting the loading.
  
  private void registerImage(String imageFile,
                             boolean preload) {
    try {
      plate = getToolkit().getImage(new URL(imageFile));
      if (preload)
        prepareImage(plate, this);
    } catch(MalformedURLException mue) {
      System.out.println("Bad URL: " + mue);
    }
  }

  // Show elapsed time in textfield.
  
  private void showTime() {
    timeField.setText("Elapsed Time: " + elapsedTime()
                      + " seconds.");
  }

  // Time in seconds since button clicked.

  private double elapsedTime() {
    double delta =
      (double)(System.currentTimeMillis() - start);
    return(delta/1000.0);
  }
}

