/* 
 * Copyright (c) 1999-2002, Xiaoping Jia.  
 * All Rights Reserved. 
 */

import java.awt.*;

/**
 *  An applet that displays a text banner that moves horizontally from right to left. 
 *  When the banner moves completely off the left end of the viewing area, 
 *  it reappears at the right end
 */
public class ScrollingBanner
        extends java.applet.Applet implements Runnable {

  protected Thread bannerThread;
  protected String text;
  protected Font font = new java.awt.Font("Sans serif", Font.BOLD, 24);    
  protected int x, y;
  protected int delay = 100;
  protected int offset = 1;
  protected Dimension d;

  public void init() {
    // get parameters "delay" and "text"
    String att = getParameter("delay");
    if (att != null) {
      delay = Integer.parseInt(att);
    }
    att = getParameter("text");
    if (att != null) {
      text = att;
    } else {
      text = "Scrolling banner.";
    }

    // set initial position of the text
    d = getSize();
    x = d.width;
    y = font.getSize();
  }


  public void paint(Graphics g) {
    // get the font metrics to determine the length of the text
    g.setFont(font);
    FontMetrics fm = g.getFontMetrics();
    int length = fm.stringWidth(text);

    // adjust the position of text from the previous frame
    x -= offset;

    // if the text is completely off to the left end
    // move the position back to the right end
    if (x < -length)
      x = d.width;

    // set the pen color and draw the background
    g.setColor(Color.black);
    g.fillRect(0,0,d.width,d.height);

    // set the pen color, then draw the text
    g.setColor(Color.green);
    g.drawString(text, x, y);
  }

  public void start() {
    bannerThread = new Thread(this);
    bannerThread.start();
  }

  public void stop() {
    bannerThread = null;
  }

  public void run() {
    while (Thread.currentThread() == bannerThread) {
      try {
        Thread.currentThread().sleep(delay);
      }
      catch (InterruptedException e) {}
      repaint();
    }
  }

}