
import java.awt.*;
import java.util.StringTokenizer;

public class Blink4 extends java.applet.Applet implements Runnable {
  Thread blinkThread;
  String blinkingtext;
  Font font;
  int speed;

  public void init() {
    font = new Font("Dialog", Font.ITALIC, 38);
    speed = 300;
    blinkingtext = "This is a simple blinking text applet for demonstration in SE 450"; 
  }
    
  public void paint(Graphics g) {
    int x = 0, y = font.getSize(), space;
    int red = (int)(Math.random() * 200);
    int green = (int)(Math.random() * 150);
    int blue = (int)(Math.random() * 256);
    Dimension d = getSize();
    
    g.setColor(Color.black);
    g.setFont(font);
    FontMetrics fm = g.getFontMetrics();
    space = fm.stringWidth(" ");
    for (StringTokenizer t = new StringTokenizer(blinkingtext); 
	 t.hasMoreTokens() ; ) {
      String word = t.nextToken();
      int w = fm.stringWidth(word) + space;
      if (x + w > d.width) {
	x = 0;
	y += font.getSize();
      }
      if (Math.random() < 0.5) {
	g.setColor(new Color((red + y * 30) % 256, 
			     (green + x / 3) % 256, 
			     blue));
      } else {
	g.setColor(getBackground());
      }
      g.drawString(word, x, y);
      x += w;
    }
  }
  
  public void start() {
    blinkThread = new Thread(this);
    blinkThread.start();
  }
  
  public void stop() {
    blinkThread = null;
  }
  
  public void run() {
    while (Thread.currentThread() == blinkThread) {
      repaint();
      try { 
	Thread.currentThread().sleep(speed); 
      } 
      catch (InterruptedException e){}
    }
  }
}


