Source of ScrollingBanner.java


  1: /* 
  2:  * Copyright (c) 1999-2002, Xiaoping Jia.  
  3:  * All Rights Reserved. 
  4:  */
  5: 
  6: import java.awt.*;
  7: 
  8: /**
  9:  *  An applet that displays a text banner that moves horizontally from right to left. 
 10:  *  When the banner moves completely off the left end of the viewing area, 
 11:  *  it reappears at the right end
 12:  */
 13: public class ScrollingBanner
 14:         extends java.applet.Applet implements Runnable {
 15: 
 16:   protected Thread bannerThread;
 17:   protected String text;
 18:   protected Font font = new java.awt.Font("Sans serif", Font.BOLD, 24);    
 19:   protected int x, y;
 20:   protected int delay = 100;
 21:   protected int offset = 1;
 22:   protected Dimension d;
 23: 
 24:   public void init() {
 25:     // get parameters "delay" and "text"
 26:     String att = getParameter("delay");
 27:     if (att != null) {
 28:       delay = Integer.parseInt(att);
 29:     }
 30:     att = getParameter("text");
 31:     if (att != null) {
 32:       text = att;
 33:     } else {
 34:       text = "Scrolling banner.";
 35:     }
 36: 
 37:     // set initial position of the text
 38:     d = getSize();
 39:     x = d.width;
 40:     y = font.getSize();
 41:   }
 42: 
 43: 
 44:   public void paint(Graphics g) {
 45:     // get the font metrics to determine the length of the text
 46:     g.setFont(font);
 47:     FontMetrics fm = g.getFontMetrics();
 48:     int length = fm.stringWidth(text);
 49: 
 50:     // adjust the position of text from the previous frame
 51:     x -= offset;
 52: 
 53:     // if the text is completely off to the left end
 54:     // move the position back to the right end
 55:     if (x < -length)
 56:       x = d.width;
 57: 
 58:     // set the pen color and draw the background
 59:     g.setColor(Color.black);
 60:     g.fillRect(0,0,d.width,d.height);
 61: 
 62:     // set the pen color, then draw the text
 63:     g.setColor(Color.green);
 64:     g.drawString(text, x, y);
 65:   }
 66: 
 67:   public void start() {
 68:     bannerThread = new Thread(this);
 69:     bannerThread.start();
 70:   }
 71: 
 72:   public void stop() {
 73:     bannerThread = null;
 74:   }
 75: 
 76:   public void run() {
 77:     while (Thread.currentThread() == bannerThread) {
 78:       try {
 79:         Thread.currentThread().sleep(delay);
 80:       }
 81:       catch (InterruptedException e) {}
 82:       repaint();
 83:     }
 84:   }
 85: 
 86: }