import java.awt.*;
import java.applet.Applet;

public class FlowText extends Applet implements Runnable {
    String text = "Please input a text as a parameter \"text\"";
    Color bgcl;
    int step = 1;
    int pace = 10;
    int index = 0;
    int textlength;

    // animation controler
    Thread animator;

    // double buffering
    Image imgbuf;
    Dimension imgbufsize;
    Graphics gb;

    public void init() {
      String str, ppace, pstep, bgcolor;
      if ((str = getParameter("text")) != null) {
	text = str;
      }
      if ((ppace = getParameter("pace")) != null) {
	pace = Integer.valueOf(ppace).intValue();
	if (pace < 5) {
	  pace = 5;
	}
      }
      if ((pstep = getParameter("step")) != null) {
	step = Integer.valueOf(pstep).intValue();
	if (step < 1) {
	  step = 1;
	}
      }
      if ((bgcolor = getParameter("bgstr")) != null) {
	String r, g, b;
	r = bgcolor.substring(0,2);
	g = bgcolor.substring(2,4);
	b = bgcolor.substring(4,6);
	bgcl = new Color(Integer.parseInt(r,16),
			 Integer.parseInt(g,16),
			 Integer.parseInt(b,16));
      } else {
	bgcl = getBackground();
      }
      textlength = getGraphics().getFontMetrics().stringWidth(text);
    }
    public void start() {
      animator = new Thread(this);
      animator.start();
    }
    public void stop() {
      animator.stop();
      animator = null;
    }
    public void run() {
      Thread me = Thread.currentThread();
      while (animator == me) {
	try {
	  Thread.sleep(pace);
	} catch (InterruptedException e) {
	  break;
	}
	synchronized (this) {
	  index++;
	  if (index >= (textlength + size().width)/step) {
	    index = 0;
	  }
	}
	repaint();
      }
    }
    public synchronized void update(Graphics g) {
      Dimension d = size();
      if ((imgbuf == null) ||
	   (d.width != imgbufsize.width) ||
	   (d.height != imgbufsize.height)) {
	imgbuf = createImage(d.width, d.height);
	imgbufsize = d;
	gb = imgbuf.getGraphics();
	gb.setFont(getFont());
      }
      gb.setColor(bgcl);
      gb.fillRect(0,0,d.width,d.height);
      gb.setColor(getForeground());
      gb.drawString(text,d.width-index*step, 10);

      g.drawImage(imgbuf,0,0,this);
    }
}
