home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / javafile / ch03 / CrazyText.java < prev    next >
Encoding:
Java Source  |  1998-12-14  |  2.0 KB  |  80 lines

  1. import java.applet.Applet;
  2. import java.awt.*;
  3.  
  4. /*
  5.  * application/applet class
  6.  */
  7. public class CrazyText extends Applet {
  8.  
  9. String text = "Java";  // string to be displayed
  10. int delta = 5;         // "craziness" factor: max pixel offset
  11. String fontName = "TimesRoman";
  12. int fontSize = 36;
  13.  
  14. char chars[];          // individual chars in 'text'
  15. int positions[];       // base horizontal position for each char
  16. FontMetrics fm;
  17.  
  18. /*
  19.  * called when the applet is loaded
  20.  * creates a font and initializes positions of characters
  21.  */
  22. public void init() {
  23.  
  24.       int fontStyle = Font.BOLD + Font.ITALIC;
  25.       setFont(new Font(fontName, fontStyle, fontSize));
  26.       fm = getFontMetrics(getFont());
  27.  
  28.       chars = new char[text.length()];
  29.       text.getChars(0, text.length(), chars, 0);
  30.  
  31.       positions = new int[text.length()];
  32.       for (int i = 0; i < text.length(); i++) {
  33.             positions[i] = fm.charsWidth(chars, 0, i) + 20;
  34.       }
  35. }
  36.  
  37. /*
  38.  * draws the characters and forces a repaint 100ms later
  39.  * @param g - destination graphics object
  40.  */
  41. public void paint (Graphics g) {
  42.  
  43.       int x, y;
  44.       g.setColor (new Color((float) Math.random(),
  45.                   (float) Math.random(),
  46.                   (float) Math.random()));
  47.       for (int i = 0; i < text.length(); i++) {
  48.             x = (int)(Math.random() * delta * 2) + positions[i];
  49.             y = (int)(Math.random() * delta * 2) + fm.getAscent() - 1;
  50. g.drawChars (chars, i, 1, x, y); 
  51.       }
  52.       repaint (100);
  53. }
  54.  
  55. /*
  56.  * override default update() method to eliminate
  57.  * erasing of the panel
  58.  */   
  59. public void update (Graphics g) {
  60.       paint (g); 
  61. }
  62.  
  63. /*
  64.  * application entry point
  65.  * create a window frame and add the applet inside
  66.  * @param args[] - command line arguments
  67.  */
  68. public static void main (String args[]) {
  69.  
  70.       Frame f = new Frame ("Crazy");
  71.       CrazyText crazy = new CrazyText ();
  72.       
  73.       f.setSize (130, 80);
  74.       f.add ("Center", crazy);
  75.       f.show ();
  76.       crazy.init ();
  77. }
  78. }
  79.  
  80.