home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / code / ch03.txt < prev    next >
Text File  |  1998-12-14  |  29KB  |  1,289 lines

  1. Sine.java:
  2.  
  3. import java.applet.Applet;
  4. import java.awt.*;
  5.  
  6. /**
  7.  * Sine curve applet/application
  8.  * Draws one cycle of a sine curve.
  9.  */
  10. public class Sine extends Applet {
  11.  
  12. /*
  13.  * width and height of the applet panel
  14.  */
  15. int width, height;
  16.  
  17. /*
  18.  * init() is called when the applet is loaded
  19.  * just get the width and height and save it
  20.  */
  21. public void init () {
  22.  
  23.        setLayout(null);
  24.        width = 300;
  25.        height = 300;
  26.        setSize(width, height);
  27. }
  28.  
  29. /**
  30.  * paint() does the drawing of the axes and sine curve
  31.  * @param g - destination graphics object
  32.  */
  33. public void paint (Graphics g) {
  34.  
  35.        int x, x0;
  36.        double y0, y, A, f, t, offset;
  37.        
  38.        A = (double) height / 4; 
  39.        f = 2;
  40.        offset = (double) height / 2;
  41.        x0 = 0;
  42.        y0 = offset;
  43.        
  44.        g.drawLine (x0, (int) y0, width, (int) y0);
  45.        g.drawLine (width/2, 0, width/2, height);
  46.        for (x=0; x<width; x+=1) {
  47.               t = (double) x / ((double) width);
  48.               y = offset - A * Math.sin (2 * Math.PI * f * t);
  49.               g.drawLine (x0, (int) y0, x, (int) y);
  50.               x0 = x;
  51.               y0 = y;
  52.        }
  53. }
  54. }
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61. Lines.java:
  62.  
  63. import java.applet.Applet;
  64. import java.awt.*;
  65.  
  66. /**
  67.  * class LineColors holds 24 color values
  68.  */
  69. class LineColors {
  70.  
  71. /**
  72.  * color[] array holds the colors to be used
  73.  */
  74. Color color[];
  75.  
  76. /**
  77.  * class constructor
  78.  * initializes the color array using an arbitrary algorithm
  79.  */
  80. public LineColors () {
  81.  
  82.        color = new Color[24];
  83.        int i, rgb;
  84.  
  85.        rgb = 0xff;
  86.        for (i=0; i<24; i+=1) {
  87.               color[i] = new Color (rgb);
  88.               rgb <<= 1;
  89.               if ((rgb & 0x1000000) != 0) {
  90.                      rgb |= 1;
  91.                      rgb &= 0xffffff;
  92.               }
  93.        }
  94. }
  95. }
  96.  
  97. /**
  98.  * class describing one line segment
  99.  */
  100. class Segment {
  101.  
  102. /*
  103.  * x1, y1 - starting coordinates for this segment
  104.  * x2, y2 - ending coordinates for this segment
  105.  * dx1,...dy2 - velocities for the endpoints
  106. * whichcolor - the current index into color array
  107.  * width, height - width and height of bounding panel
  108.  * LC - instance of LineColors class
  109.  */
  110. double x1, y1, x2, y2;
  111. double dx1, dy1, dx2, dy2;
  112. int whichcolor, width, height;
  113. LineColors LC;
  114.  
  115. /**
  116.  * class constructor
  117.  * initialize endpoints and velocities to random values
  118.  * @param w - width of bounding panel
  119.  * @param h - height of bounding panel
  120.  * @param c - starting color index
  121.  * @param lc - instance of LineColors class
  122.  */
  123. public Segment (int w, int h, int c, LineColors lc) {
  124.  
  125.        whichcolor = c;
  126.        width = w;
  127.        height = h;
  128.        LC = lc;
  129.        x1 = (double) w * Math.random ();
  130.        y1 = (double) h * Math.random ();
  131.        x2 = (double) w * Math.random ();
  132.        y2 = (double) h * Math.random ();
  133.  
  134.        dx1 = 5 - 10 * Math.random ();
  135.        dy1 = 5 - 10 * Math.random ();
  136.        dx2 = 5 - 10 * Math.random ();
  137.        dy2 = 5 - 10 * Math.random ();
  138. }
  139.  
  140. /*
  141.  * increment color index
  142.  * calculate the next endpoint position for this segment
  143.  */
  144. void compute () {
  145.  
  146.        whichcolor += 1;
  147.        whichcolor %= 24;
  148.        
  149.        x1 += dx1;
  150.        y1 += dy1;
  151.        x2 += dx2;
  152.        y2 += dy2;
  153.  
  154.        if (x1 < 0 || x1 > width) dx1 = -dx1;
  155.        if (y1 < 0 || y1 > height) dy1 = -dy1;
  156.        if (x2 < 0 || x2 > width) dx2 = -dx2;
  157.        if (y2 < 0 || y2 > height) dy2 = -dy2; 
  158. }
  159.  
  160. /**
  161.  * draw the line segment using the current color
  162.  * @param g - destination graphics object
  163.  */
  164. void paint (Graphics g) {
  165.  
  166.        g.setColor (LC.color [whichcolor]);
  167.        g.drawLine ((int) x1, (int) y1, (int) x2, (int) y2);
  168. }
  169. }
  170.  
  171. /**
  172.  * The applet/application proper
  173.  */
  174. public class Lines extends Applet {
  175.  
  176. /*
  177.  * Nlines - number of line segments to be displayed
  178.  * lines - array of instances of Segment class
  179.  * LC - instance of LineColors class
  180.  */
  181. int width,height;
  182. final int NLines = 4;
  183. Segment lines[] = new Segment[NLines];
  184. LineColors LC = new LineColors ();
  185.  
  186. /**
  187.  * init is called when the applet is loaded
  188.  * save the width and height
  189.  * create instances of Segment class
  190.  */
  191. public void init () {
  192.  
  193.        setLayout(null);
  194.        width = 300;
  195.        height = 300;
  196.        setSize(width, height);
  197.        
  198.        int i;
  199.        for (i=0; i<NLines; i+=1)
  200.               lines[i] = new Segment (width, 
  201. σheight, (2*i) % 24, LC);
  202. }
  203.  
  204. /**
  205.  * recompute the next endpoint coordinates for each line
  206.  * invoke paint() method for each line
  207.  * call repaint() to force painting 50ms. later
  208.  * @param g - destination graphics object
  209.  */
  210. public void paint (Graphics g) {
  211.  
  212.        int i;
  213.        for (i=0; i<NLines; i+=1) {
  214.               lines[i].compute ();
  215.               lines[i].paint (g);
  216.        }
  217.        repaint (50); 
  218. }
  219.  
  220. }
  221.  
  222.  
  223.  
  224.  
  225.  
  226.  
  227.  
  228.  
  229. DrawApp.java:
  230.  
  231. import java.applet.Applet;
  232. import java.awt.*;
  233. import java.awt.event.*;
  234. import java.io.*;
  235. import java.util.StringTokenizer;
  236.  
  237. /**
  238.  * class describing a shape
  239.  */
  240. class Shape {
  241.  
  242. /**
  243.  * constants for the shape type
  244.  */
  245. static final int rectType = 1;
  246. static final int ovalType = 2;
  247. static final int arcType = 3;
  248. static final int polyType = 4;
  249.  
  250. /*
  251.  * the shape type
  252.  */
  253. int type;
  254.  
  255. /*
  256.  * color for this shape
  257.  */
  258. Color color;
  259. static final int MaxPoints = 10;
  260.  
  261. /*
  262.  * arrays of x and y points for this shape
  263.  */
  264. int xp[] = new int[MaxPoints];
  265. int yp[] = new int[MaxPoints];
  266.  
  267. /*
  268.  * the number of points in this shape
  269.  */
  270. int npoints;
  271.  
  272. /**
  273.  * shape constructor
  274.  * saves parameters
  275.  * @param tp - shape type
  276.  * @param n - number of points
  277.  * @param pts[] - array of endpoints
  278.  * @param c - color of the shape
  279.  */
  280. public Shape (int tp, int n, int pts[], Color c) {
  281.  
  282.        int i;
  283.       type = tp;
  284.       color = c;
  285.       npoints = n < MaxPoints ? n : MaxPoints;
  286.       if (type == polyType) {
  287.             npoints >>= 1;
  288.             for (i=0; i<npoints; i+=1) {
  289.                   xp[i] = pts[i << 1];
  290.                   yp[i] = pts[(i << 1) +1];
  291.             }
  292.       } else {
  293.             for (i=0; i<npoints; i+=1)
  294.                   xp[i] = pts[i];
  295.       }
  296. }
  297.  
  298. /**
  299.  * draw the shape
  300.  * @param g - destination graphics object
  301.  */
  302. void paint (Graphics g) {
  303.  
  304.       g.setColor (color);
  305.       switch (type) {
  306.  
  307.       case rectType:
  308.             g.drawRect (xp[0], xp[1], xp[2], xp[3]);
  309.             break;
  310.  
  311.       case ovalType:
  312.             g.drawOval (xp[0], xp[1], xp[2], xp[3]);
  313.             break;
  314.  
  315.       case arcType: 
  316.             g.drawArc (xp[0], xp[1], xp[2], xp[3], xp[4], xp[5]);
  317. break;
  318.  
  319.       case polyType:
  320.             g.drawPolygon (xp, yp, npoints);
  321.             break;
  322.       }
  323. }
  324. }
  325.  
  326. /**
  327.  * application class proper
  328.  */
  329. public class DrawApp extends Panel {
  330.  
  331. /*
  332.  * the maximum number of shapes allowed
  333.  */
  334. static final int MaxShapes = 25;
  335.  
  336. /*
  337.  * nshapes - the number of shapes read in
  338.  * nlines - the line number in the input file
  339.  */
  340. static int nshapes, nlines = 0;
  341.  
  342. /*
  343.  * array of instances of class shape
  344.  */
  345. static Shape shapes[] = new Shape[MaxShapes];
  346.  
  347. /**
  348.  * invoke paint() method for each shape
  349.  * @param g - destination graphics object
  350.  */
  351. public void paint (Graphics g) {
  352.  
  353.       int i;
  354.       for (i=0; i<nshapes; i+=1)
  355.             shapes[i].paint (g);
  356. }
  357.  
  358. /**
  359.  * application entry point
  360.  * @param args - command-line arguments
  361.  */
  362. public static void main (String args[]) {
  363.  
  364.       String buf;
  365.       FileInputStream fs=null;
  366.       int i, type = 0;
  367.  
  368.       if (args.length != 1) {
  369.             System.out.println ("usage: java DrawApp <file>");
  370.             System.exit (1);
  371.       }
  372.  
  373. /*
  374.  * Try to open the file specified by args[0]
  375.  */
  376.       try {
  377.             fs = new FileInputStream (args[0]);
  378.       } catch (Exception e) {
  379.             System.out.println (e);
  380.             System.exit (1);
  381.       }
  382.  
  383. /*
  384.  * Create a DataInputStream BufferedReader 
  385.  * associated with FileInputStream fs
  386. */
  387.       BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
  388. String token;
  389.       Color color = Color.white;
  390.       int pts[] = new int[2 * Shape.MaxPoints];
  391.  
  392. /*
  393.  * loop until end of file or error
  394.  * read a line and parse it
  395.  */
  396.       while (true) {
  397.             try {
  398.                   buf = ds.readLine ();      // read 1 line
  399.                   if (buf == null) break;
  400.             } catch (IOException e) {
  401.                   System.out.println (e);      
  402. break;
  403.             }
  404.             nlines += 1;
  405.             StringTokenizer st = new StringTokenizer (buf); 
  406.             token = st.nextToken ();
  407.             if (token.equals ("white")) {
  408.                   color = Color.white;
  409.                   token = st.nextToken ();
  410.             } else if (token.equals ("lightgray")) {
  411.                   color = Color.lightGray;
  412.                   token = st.nextToken ();
  413.             } else if (token.equals ("gray")) {
  414.                   color = Color.gray;
  415.                   token = st.nextToken ();
  416.             } else if (token.equals ("darkgray")) {
  417.                   color = Color.darkGray;
  418.                   token = st.nextToken ();
  419.             } else if (token.equals ("black")) {
  420.                   color = Color.black;
  421.                   token = st.nextToken ();
  422.             } else if (token.equals ("red")) {
  423.                   color = Color.red;
  424.                   token = st.nextToken ();
  425.             } else if (token.equals ("pink")) {
  426.                   color = Color.pink;
  427.                   token = st.nextToken ();
  428.             } else if (token.equals ("orange")) {
  429.                   color = Color.orange;
  430.                   token = st.nextToken ();
  431.             } else if (token.equals ("yellow")) {
  432.                   color = Color.yellow;
  433.                   token = st.nextToken ();
  434.             } else if (token.equals ("green")) {
  435.                   color = Color.green;
  436.                   token = st.nextToken ();
  437.             } else if (token.equals ("magenta")) {
  438.                   color = Color.magenta;
  439.                   token = st.nextToken ();
  440.             } else if (token.equals ("cyan")) {
  441.                   color = Color.cyan;
  442.                   token = st.nextToken ();
  443.             } else if (token.equals ("blue")) {
  444.                   color = Color.blue;
  445.                   token = st.nextToken ();
  446.             } else {
  447.                   System.out.println ("Unknown color: "+token);
  448.                   System.out.println ("line "+nlines);
  449.                   System.exit (1);
  450.             }
  451.  
  452.             int npoints = 0;
  453.             if (token.equals ("rect")) {
  454.                   npoints = getInt (st, pts, 4); 
  455.                   type = Shape.rectType;
  456.             } else if (token.equals ("oval")) {
  457.                   npoints = getInt (st, pts, 4);
  458.                   type = Shape.ovalType;
  459.             } else if (token.equals ("arc")) {
  460.                   npoints = getInt (st, pts, 6);
  461.                   type = Shape.arcType;
  462.             } else if (token.equals ("poly")) {
  463.                   npoints = getInt (st, pts, Shape.MaxPoints);
  464.                   type = Shape.polyType;
  465.             } else {
  466.                   System.out.println ("Unknown shape: "+token);
  467.                   System.out.println ("line "+nlines);
  468.                   System.exit (1);
  469.             }
  470.             shapes[nshapes++] = new Shape (type, npoints, pts, color);
  471. }
  472. /*
  473.  * close can throw an exception also; catch it for completeness
  474.  */
  475.       try {
  476.             fs.close ();
  477.       } catch (IOException e) {
  478.             System.out.println (e);
  479.       }
  480.  
  481.       Frame f = new Frame ("Drawing shapes");
  482.       DrawApp drawApp = new DrawApp ();
  483.  
  484.       f.setSize(410, 430);
  485.       f.addWindowListener(new WindowCloser());
  486.       f.add ("Center", drawApp);
  487.       f.show ();
  488. }
  489.  
  490. /**
  491.  * parse points
  492.  * @param st - StringTokenizer for current line
  493.  * @param pts[] - array of points to be returned
  494.  * @param nmax - maximum number of points to accept
  495.  */
  496. static int getInt (StringTokenizer st, int pts[], int nmax) {
  497.  
  498.       int i;
  499.       String token;
  500.  
  501.       for (i=0; i<nmax; i+=1) {
  502.             if (st.hasMoreTokens () == false) break;
  503.             token = st.nextToken ();
  504.             try {
  505.                   pts[i] = Integer.valueOf (token).intValue ();
  506.             } catch (NumberFormatException e) {
  507.                   System.out.println (e);
  508.                   System.out.println ("line "+nlines);
  509.                   System.exit (1);
  510.             }
  511.       }
  512.       return i;
  513. }
  514. }
  515. class WindowCloser extends WindowAdapter
  516. {
  517.     public void windowClosing(WindowEvent e)
  518.     {
  519.         Window win = e.getWindow();
  520.         win.setVisible(false);
  521.         win.dispose();
  522.         System.exit(0);
  523.     }//windowClosing
  524. }//class WindowCloser
  525.  
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.  
  533. ChartApp.java:
  534.  
  535. import java.applet.Applet;
  536. import java.awt.*;
  537.  
  538. /**
  539.  * parent class
  540.  */
  541. class Chart {
  542.  
  543. /*
  544.  * x and y positions of the upper-left of the chart
  545.  * nvalues - number of values for this chart
  546.  */
  547. int xpos, ypos, nvalues;
  548.  
  549. /*
  550.  * width and height of this chart
  551.  */
  552. int width, height;
  553.  
  554. /*
  555.  * maximum number of values allowed
  556.  */
  557. final int MaxValues = 10;
  558.  
  559. /*
  560.  * data values for this chart
  561.  */
  562. double values[] = new double[MaxValues];
  563.  
  564. /*
  565.  * color associated with each value
  566.  */
  567. Color colors[] = new Color[MaxValues];
  568.  
  569. /*
  570.  * sum total of values, used for scaling purposes
  571.  */
  572. double total;
  573.  
  574. /**
  575.  * class constructor
  576.  * save values and normalizes them so that the max. value is 1.0
  577.  * @param x, y - top-left coordinates
  578.  * @param w, h - width and height
  579.  * @param n - number of points
  580.  * @param val[] - array of values
  581.  * @param c[] - array of colors corresponding to values
  582.  */
  583. public Chart (int x, int y, int w, int h, int n, double val[], Color c[]) {
  584.  
  585.       int i;
  586.       double extreme; 
  587.       
  588.       xpos = x;
  589.       ypos = y;
  590.       width = w;
  591.       height = h;
  592.       nvalues = n;
  593.       if (nvalues > MaxValues) nvalues = MaxValues;
  594.       extreme = 0.0;
  595.       for (i=0; i<nvalues; i+=1) {
  596.             if (Math.abs (val[i]) > extreme)
  597.                   extreme = Math.abs (val[i]);
  598.             colors[i] = c[i]; 
  599.       }
  600.       extreme = 1/extreme;
  601.       total = 0;
  602.       for (i=0; i<nvalues; i+=1) {
  603.             values[i] = extreme * val[i];
  604.             total += values[i];
  605.       }
  606. }
  607. }
  608.  
  609. /**
  610.  * class implements a bar chart
  611.  */
  612. class BarChart extends Chart {
  613.  
  614. /**
  615.  * constructor just calls Chart constructor
  616.  * @param x, y - top left coordinates
  617.  * @param w, h - width and height
  618.  * @param n - number of points
  619.  * @param val[] - array of values
  620.  * @param c[] - array of colors corresponding to values
  621.  */
  622. public BarChart (int x, int y, int w, int h, int n, double val[], Color c[]) {
  623.  
  624.       super (x, y, w, h, n, val, c);
  625. }
  626.  
  627. /**
  628.  * need to add a paint method
  629.  * draws the bar chart using fill3DRect
  630.  * @param g - destination graphics object
  631.  */
  632. void paint (Graphics g) {
  633.  
  634.       int i;
  635.       int barwidth = 3 * width / (4 * nvalues);
  636.       int bardx = width / nvalues;
  637.       int x, y, h;
  638.  
  639.       g.setColor (Color.black);
  640.       g.fillRect (xpos, ypos-height, width, height);
  641.       for (i=0; i<nvalues; i+=1) {
  642.             g.setColor (colors[i]);
  643.             x = xpos + bardx*i;
  644.             h = (int) (values[i] * height);
  645.             y = ypos - h;
  646.             g.fill3DRect (x, y, barwidth, h, true);
  647.       }
  648. }
  649. }
  650.  
  651. /**
  652.  * class implements a pie chart
  653.  */
  654. class PieChart extends Chart {
  655.  
  656. /**
  657.  * class constructor just calls Chart constructor
  658.  * @param x, y - top-left coordinates
  659.  * @param w, h - width and height
  660.  * @param n - number of points
  661.  * @param val[] - array of values
  662.  * @param c[] - array of colors corresponding to values
  663.  */
  664. public PieChart (int x, int y, int w, int h, int n, double val[], Color c[]) {
  665.  
  666.       super (x, y, w, h, n, val, c); 
  667. }
  668.  
  669. /**
  670.  * need to add a paint method
  671.  * draws the pie chart using fillArc
  672.  * @param g - destination graphics object
  673.  */
  674. void paint (Graphics g) {
  675.  
  676.       int i, y;
  677.       int startAngle, arcAngle;
  678.       
  679.       startAngle = 0;
  680.       y = ypos - height;
  681.       for (i=0; i<nvalues; i+=1) {
  682.             arcAngle = (int) (360.0 * values[i] / total);
  683.             g.setColor (colors[i]);
  684.             g.fillArc (xpos, y, width, height, startAngle, arcAngle); 
  685. startAngle += arcAngle;
  686.       }
  687. }
  688. }
  689.  
  690. /**
  691.  * the applet/application  proper
  692.  */
  693. public class ChartApp extends Applet {
  694.  
  695. /*
  696.  * width and height of the bounding panel
  697.  */
  698. int width, height;
  699.  
  700. /*
  701.  * instances of BarChart and PieChart
  702.  */
  703. BarChart bc1;
  704. PieChart pc1;
  705.  
  706. /*
  707.  * called when applet is loaded
  708.  * generate random values and plot them
  709.  */
  710. public void init () {
  711.  
  712.       int i;
  713.       double values[] = new double[5];
  714.       Color colors[] = new Color[5];
  715.       
  716.       width = 410; 
  717.       height = 230;
  718.       colors[0] = Color.blue;
  719.       colors[1] = Color.orange;
  720.       colors[2] = Color.yellow;
  721.       colors[3] = Color.green;
  722.       colors[4] = Color.magenta;
  723.  
  724.       for (i=0; i<5; i+=1) values[i] = Math.random () + 0.001;
  725.       int w = (width-40)/2;
  726.       int h = height-20;
  727.       bc1 = new BarChart (10, height-10, w, h, 5, values, colors);
  728. pc1 = new PieChart (width/2, height-10, w, h, 5, values, colors); 
  729. }
  730.  
  731. /**
  732.  * invoke the chart paint methods
  733.  * @param g - destination graphics object
  734.  */
  735. public void paint (Graphics g) {
  736.  
  737.       bc1.paint (g);
  738.       pc1.paint (g);
  739. }
  740.  
  741. /**
  742.  * application entry point
  743.  * create a window frame and add the applet inside
  744.  * @param args[] - command-line arguments
  745.  */
  746. public static void main (String args[]) {
  747.  
  748.       Frame f = new Frame ("Charts");
  749.       ChartApp chart = new ChartApp ();
  750.       
  751.       f.setSize (410, 230);
  752.       f.add ("Center", chart);
  753.       f.show ();
  754.       chart.init ();
  755.       chart.start ();
  756. }
  757. }
  758.  
  759.  
  760.  
  761.  
  762.  
  763.  
  764.  
  765.  
  766. ScrollApp.java:
  767.  
  768. import java.applet.Applet;
  769. import java.awt.*;
  770.  
  771. /**
  772.  * a class that handles scrolling text
  773.  */
  774. class Scroll {
  775.  
  776. /*
  777.  * x and y coordinates of starting point
  778.  */
  779. int xstart, ystart;
  780.  
  781. /*
  782.  * width and height of bounding panel
  783.  */
  784. int width, height;
  785.  
  786. /*
  787.  * text to be scrolled
  788.  */
  789. String text; 
  790.  
  791. /*
  792.  * x and y velocities, respectively
  793.  */
  794. int deltaX, deltaY;
  795.  
  796. /*
  797.  * current x and y position of the text
  798.  */
  799. int xpos, ypos;
  800.  
  801. /*
  802.  * the color of the text
  803.  */
  804. Color color;
  805.  
  806. /**
  807.  * class constructor just saves arguments
  808.  * @param x, y - starting coordinates
  809.  * @param dx, dy - x and y velocities
  810.  * @param w, h - width and height of bounding panel
  811.  * @param t - the text string
  812.  * @param c - color of the text
  813.  */
  814. public Scroll (int x, int y, int dx, int dy, int w, int h, String t, Color c) {
  815.  
  816.       xstart = x;
  817.       ystart = y;
  818.       width = w;
  819.       height = h;
  820.       text = t;
  821.       deltaX = dx;
  822.       deltaY = dy;
  823.       color = c;
  824.       xpos = xstart;
  825.       ypos = ystart;
  826. }
  827.  
  828. /*
  829.  * draw the text at the current position
  830.  * advance the position and reinitialize outside bounding panel
  831.  * @param g - destination graphics object
  832.  */
  833. void paint (Graphics g) {
  834.  
  835.       g.setColor (color);
  836.       g.drawString (text, xpos, ypos);
  837.       xpos += deltaX;
  838.       ypos += deltaY;
  839.  
  840.       FontMetrics fm = g.getFontMetrics ();
  841.       int textw = fm.stringWidth (text);
  842.       int texth = fm.getHeight ();
  843.       if (deltaX < 0 && xpos < -textw) xpos = xstart;
  844.       if (deltaX > 0 && xpos > width) xpos = xstart;
  845.       if (deltaY < 0 && ypos < 0) ypos = ystart;
  846.       if (deltaY > 0 && ypos > height+texth) ypos = ystart;
  847. }
  848. }
  849.  
  850. /**
  851.  * the applet/application proper
  852.  */
  853. public class ScrollApp extends Applet {
  854.  
  855. /*
  856.  * width and height of the bounding panel
  857.  */
  858. int width, height;
  859.  
  860. /*
  861.  * instances of Scroll for demonstration
  862.  */
  863. Scroll left, right, up, down, diag;
  864.  
  865. /*
  866.  * called when the applet is loaded
  867.  * create new instances of Scroll
  868.  */      
  869. public void init () {
  870.  
  871.  
  872.       width = 410;
  873.       height = 230;
  874.  
  875.       left = new Scroll (400, 50, -5, 0, width, height,
  876.             "Moving left", Color.red);
  877.       right = new Scroll (0, 150, 5, 0, width, height,
  878.             "Moving right", Color.green);
  879.       up = new Scroll (100, 200, 0, -5, width, height,
  880.             "Moving up", Color.blue);
  881.       down = new Scroll (200, 0, 0, 5, width, height,
  882.             "Moving down", Color.cyan);
  883.       diag = new Scroll (0, 0, 7, 3, width, height,
  884.             "Moving diagonally", Color.magenta); 
  885. }
  886.  
  887. /*
  888.  * invoke the paint method of each scrolling text instance
  889.  * force a repaint 50ms later
  890.  */
  891. public void paint (Graphics g) {
  892.  
  893.       left.paint (g);
  894.       right.paint (g);
  895.       up.paint (g);
  896.       down.paint (g);
  897.       diag.paint (g);
  898.       repaint (50);
  899. }
  900.  
  901. /*
  902.  * Application entry point
  903.  * @param args - command-line arguments
  904.  */
  905. public static void main (String args[]) {
  906.  
  907.       Frame f = new Frame ("Scrolling text");
  908.       ScrollApp scrollApp = new ScrollApp ();
  909.       
  910.       f.setSize (410, 230);
  911.       f.add ("Center", scrollApp);
  912.       f.show ();
  913.       scrollApp.init ();
  914. }
  915. }
  916.  
  917.  
  918.  
  919.  
  920.  
  921.  
  922.  
  923.  
  924. Fonts.java:
  925.  
  926. import java.applet.Applet;
  927. import java.awt.*;
  928.  
  929. /**
  930.  * Class that determines which fonts are available
  931.  */
  932. public class Fonts extends Applet {
  933.  
  934. /*
  935.  * Maximum number of fonts to display
  936.  */
  937. final int MaxFonts = 10;
  938.  
  939. /*
  940.  * Width and height of bounding panel
  941.  */
  942. int width, height;
  943.  
  944. /*
  945.  * Array of font names
  946.  */
  947. String fontName[];
  948.  
  949. /*
  950.  * Array of fonts
  951.  * Holds plain, italic, and bold for each font
  952.  */
  953. Font theFonts[] = new Font[3 * MaxFonts];
  954.  
  955. /*
  956.  * The number of fonts found
  957.  */
  958. int nfonts = 0;
  959.  
  960. /*
  961.  * Applet entry point
  962.  */
  963. public void init () {
  964.  
  965.     int i;
  966.     Dimension d = getSize ();
  967.  
  968.     width = d.width;
  969.     height = d.height;
  970.  
  971.         theFonts[0] = new Font ("Courier", Font.PLAIN, 12);
  972.         theFonts[1] = new Font ("System", Font.BOLD, 16);
  973.         theFonts[2] = new Font ("Helvetica", Font.BOLD, 18); 
  974.     }
  975.  
  976. /*
  977.  * Draw the font names.
  978.  * @param g - destination graphics object
  979.  */
  980. public void paint (Graphics g) {
  981.  
  982.     int i;
  983.  
  984.  
  985.         g.setFont (theFonts[0]);
  986.         g.drawString ("Courier", 10, 30);
  987.         g.setFont (theFonts[1]);
  988.         g.drawString ("System", 70, 70);
  989.         g.setFont (theFonts[2]);
  990.         g.drawString ("Helvetica", 150, 90);
  991.  
  992. }
  993.  
  994. /*
  995.  * Application entry point
  996.  * Creates a window frame and adds the applet inside
  997.  * @param args[] - command-line arguments
  998.  */
  999. public static void main (String args[]) {
  1000.  
  1001.     Frame f = new Frame ("Fonts");
  1002.     Fonts fonts = new Fonts ();
  1003.  
  1004.     f.setSize (250, 200);
  1005.     f.add ("Center", fonts);
  1006.     f.show ();
  1007.     fonts.init ();
  1008. }
  1009. }
  1010.  
  1011.  
  1012.  
  1013.  
  1014.  
  1015.  
  1016.  
  1017.  
  1018. CrazyText.java:
  1019.  
  1020. import java.applet.Applet;
  1021. import java.awt.*;
  1022.  
  1023. /*
  1024.  * application/applet class
  1025.  */
  1026. public class CrazyText extends Applet {
  1027.  
  1028. String text = "Java";  // string to be displayed
  1029. int delta = 5;         // "craziness" factor: max pixel offset
  1030. String fontName = "TimesRoman";
  1031. int fontSize = 36;
  1032.  
  1033. char chars[];          // individual chars in 'text'
  1034. int positions[];       // base horizontal position for each char
  1035. FontMetrics fm;
  1036.  
  1037. /*
  1038.  * called when the applet is loaded
  1039.  * creates a font and initializes positions of characters
  1040.  */
  1041. public void init() {
  1042.  
  1043.       int fontStyle = Font.BOLD + Font.ITALIC;
  1044.       setFont(new Font(fontName, fontStyle, fontSize));
  1045.       fm = getFontMetrics(getFont());
  1046.  
  1047.       chars = new char[text.length()];
  1048.       text.getChars(0, text.length(), chars, 0);
  1049.  
  1050.       positions = new int[text.length()];
  1051.       for (int i = 0; i < text.length(); i++) {
  1052.             positions[i] = fm.charsWidth(chars, 0, i) + 20;
  1053.       }
  1054. }
  1055.  
  1056. /*
  1057.  * draws the characters and forces a repaint 100ms later
  1058.  * @param g - destination graphics object
  1059.  */
  1060. public void paint (Graphics g) {
  1061.  
  1062.       int x, y;
  1063.       g.setColor (new Color((float) Math.random(),
  1064.                   (float) Math.random(),
  1065.                   (float) Math.random()));
  1066.       for (int i = 0; i < text.length(); i++) {
  1067.             x = (int)(Math.random() * delta * 2) + positions[i];
  1068.             y = (int)(Math.random() * delta * 2) + fm.getAscent() - 1;
  1069. g.drawChars (chars, i, 1, x, y); 
  1070.       }
  1071.       repaint (100);
  1072. }
  1073.  
  1074. /*
  1075.  * override default update() method to eliminate
  1076.  * erasing of the panel
  1077.  */   
  1078. public void update (Graphics g) {
  1079.       paint (g); 
  1080. }
  1081.  
  1082. /*
  1083.  * application entry point
  1084.  * create a window frame and add the applet inside
  1085.  * @param args[] - command line arguments
  1086.  */
  1087. public static void main (String args[]) {
  1088.  
  1089.       Frame f = new Frame ("Crazy");
  1090.       CrazyText crazy = new CrazyText ();
  1091.       
  1092.       f.setSize (130, 80);
  1093.       f.add ("Center", crazy);
  1094.       f.show ();
  1095.       crazy.init ();
  1096. }
  1097. }
  1098.  
  1099.  
  1100.  
  1101.  
  1102.  
  1103.  
  1104.  
  1105.  
  1106.  
  1107. Status.java:
  1108.  
  1109. import java.applet.Applet;
  1110. import java.awt.*;
  1111.  
  1112. /*
  1113.  * class to hold color values
  1114.  */
  1115. class LineColors {
  1116.  
  1117. /*
  1118.  * an array of colors proper
  1119.  */
  1120. Color color[];
  1121.  
  1122. /*
  1123.  * the constructor initializes the color array by 
  1124.  * using an arbitrary algorithm
  1125.  */
  1126. public LineColors () {
  1127.  
  1128.         color = new Color[24];
  1129.         int i, rgb;
  1130.  
  1131.         rgb = 0xff;
  1132.         for (i=0; i<24; i+=1) {
  1133.                 color[i] = new Color (rgb);
  1134.                 rgb <<= 1;
  1135.                 if ((rgb & 0x1000000) != 0) {
  1136.                         rgb |= 1;
  1137.                         rgb &= 0xffffff;
  1138.                 }
  1139.         }
  1140. }
  1141. } // class LineColors
  1142.  
  1143. /*
  1144.  * class to handle the drawing of one line segment
  1145.  */
  1146. class Segment {
  1147.  
  1148. /*
  1149.  * x1, y1 - x and y position of first endpoint
  1150.  * x2, y2 - x and y position of second endpoint
  1151.  */
  1152. double x1, y1, x2, y2;
  1153.  
  1154. /*
  1155.  * velocities of the endpoints, respectively
  1156.  */
  1157. double dx1, dy1, dx2, dy2;
  1158.  
  1159. /*
  1160.  * whichcolor - color index for this segment
  1161.  */
  1162. int whichcolor; 
  1163.  
  1164. /*
  1165.  * width and height of bounding panel
  1166.  */
  1167. int width, height;
  1168.  
  1169. /*
  1170.  * instance of LineColors
  1171.  */
  1172. LineColors LC;
  1173.  
  1174. /*
  1175.  * class constructor
  1176.  * saves arguments and initializes position and velocities
  1177.  * to random values
  1178.  * @param w, h - width and height of bounding panel
  1179.  * @param c - starting color
  1180.  * @param lc - instance of LineColor
  1181.  */
  1182. public Segment (int w, int h, int c, LineColors lc) {
  1183.  
  1184.         whichcolor = c;
  1185.         width = w;
  1186.         height = h; 
  1187.         LC = lc;
  1188.         x1 = (double) w * Math.random ();
  1189.         y1 = (double) h * Math.random ();
  1190.         x2 = (double) w * Math.random ();
  1191.         y2 = (double) h * Math.random ();
  1192.  
  1193.         dx1 = 5 - 10 * Math.random ();
  1194.         dy1 = 5 - 10 * Math.random ();
  1195.         dx2 = 5 - 10 * Math.random ();
  1196.         dy2 = 5 - 10 * Math.random ();
  1197. }
  1198.  
  1199. /*
  1200.  * increments color index and calculates new endpoint positions
  1201.  */
  1202. void compute () {
  1203.  
  1204.         whichcolor += 1;
  1205.         whichcolor %= 24;
  1206.         
  1207.         x1 += dx1;
  1208.         y1 += dy1;
  1209.         x2 += dx2;
  1210.         y2 += dy2;
  1211.  
  1212.         if (x1 < 0 || x1 > width) dx1 = -dx1;
  1213.         if (y1 < 0 || y1 > height) dy1 = -dy1;
  1214.         if (x2 < 0 || x2 > width) dx2 = -dx2;
  1215.         if (y2 < 0 || y2 > height) dy2 = -dy2; 
  1216. }
  1217.  
  1218. /**
  1219.  * prints status message showing the different colors
  1220.  * @param g - destination graphics object
  1221.  */
  1222. void paint (Graphics g) {
  1223.  
  1224.         g.setColor (LC.color [whichcolor]);
  1225.         g.drawLine ((int) x1, (int) y1, (int) x2, (int) y2);
  1226. }
  1227. } // class Segment
  1228.  
  1229. public class Status extends Applet {
  1230.  
  1231. /*
  1232.  * width and height of bounding panel
  1233.  */
  1234. int width, height;
  1235.  
  1236. /*
  1237.  * The number of lines will be set to 1 because the color values
  1238.  * displayed will be valid for only one line
  1239.  */
  1240. final int NLines = 1;
  1241.  
  1242. /*
  1243.  * array of instances of Segment
  1244.  */
  1245. Segment lines[] = new Segment[NLines];
  1246.  
  1247. /*
  1248.  * instance of LineColor
  1249.  */
  1250. LineColors LC = new LineColors ();
  1251.  
  1252. /*
  1253.  * called when applet is loaded
  1254.  * save panel dimensions and create instance of Segment
  1255.  */
  1256. public void init () {
  1257.  
  1258.        
  1259.         width = 200;
  1260.         height = 200; 
  1261.         
  1262.         int i;
  1263.         for (i=0; i<NLines; i+=1)
  1264.                 lines[i] = new Segment (width, height, (2*i) % 24, LC);
  1265. }
  1266.  
  1267. /**
  1268.  * draw the line and print status message
  1269.  * @param g - destination graphics object
  1270.  */
  1271. public void paint (Graphics g) {
  1272.  
  1273.         int i; 
  1274.         for (i=0; i<NLines; i+=1) {
  1275.                 lines[i].compute ();
  1276.                 lines[i].paint (g);
  1277.         }
  1278.         showStatus("red = "+g.getColor().getRed() + "  green = " +
  1279.                 g.getColor().getGreen() + "  blue = " +
  1280.                 g.getColor().getBlue());
  1281.  
  1282.         repaint (50);
  1283. }
  1284. }
  1285.  
  1286.  
  1287.  
  1288.  
  1289.