Thursday 19 April 2012

Simple moving banner applet program

It has been my observation that usually the moving banner programs are written with substring logic. The problem with this approach is that the message starts scrolling horizontally only between the space equivalent to length of the message. If we want a banner to scroll applet wide i.e. within the complete applet window horizontally (and not only within the space equal to length of the message), below program can be a simple solution!
  1. /*<applet code="MovingBannerApplet.class" width="400" height="400">
  2. </applet>*/
  3.  
  4. import java.applet.Applet;
  5. import java.awt.*;
  6.  
  7. public class MovingBannerApplet extends Applet implements Runnable {
  8.         String message;
  9.         int x1, x2, y, dx;
  10.  
  11.         public void init() {
  12.                 message = "This is a moving banner!";
  13.                 x1 = 0;
  14.                 x2 = -400;
  15.                 y = 200;
  16.                 dx = 1;
  17.  
  18.                 setFont(new Font("Arial", Font.BOLD, 20));
  19.                 setBackground(Color.cyan);
  20.                 setForeground(Color.red);
  21.         }
  22.  
  23.         public void start() {
  24.                 Thread t = new Thread(this);
  25.                 t.start();
  26.         }
  27.  
  28.         public void paint(Graphics g) {
  29.                 g.drawString(message, x1, y);
  30.                 g.drawString(message, x2, y);
  31.         }
  32.  
  33.         public void run() {
  34.                 try {
  35.                         while (true) {
  36.                                 Thread.sleep(50);
  37.                                 x1 += dx;
  38.                                 x2 += dx;
  39.                                 if (x1 == 400)
  40.                                         x1 = -400;
  41.                                 if (x2 == 400)
  42.                                         x2 = -400;
  43.                                 repaint();
  44.                         }
  45.                 } catch (Exception e) {
  46.                 }
  47.         }
  48. }