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

  1. import java.applet.Applet;
  2. import java.awt.*;
  3.  
  4. /**
  5.  * Sine curve applet/application
  6.  * Draws one cycle of a sine curve.
  7.  */
  8. public class Sine extends Applet {
  9.  
  10. /*
  11.  * width and height of the applet panel
  12.  */
  13. int width, height;
  14.  
  15. /*
  16.  * init() is called when the applet is loaded
  17.  * just get the width and height and save it
  18.  */
  19. public void init () {
  20.  
  21.        setLayout(null);
  22.        width = 300;
  23.        height = 300;
  24.        setSize(width, height);
  25. }
  26.  
  27. /**
  28.  * paint() does the drawing of the axes and sine curve
  29.  * @param g - destination graphics object
  30.  */
  31. public void paint (Graphics g) {
  32.  
  33.        int x, x0;
  34.        double y0, y, A, f, t, offset;
  35.        
  36.        A = (double) height / 4; 
  37.        f = 2;
  38.        offset = (double) height / 2;
  39.        x0 = 0;
  40.        y0 = offset;
  41.        
  42.        g.drawLine (x0, (int) y0, width, (int) y0);
  43.        g.drawLine (width/2, 0, width/2, height);
  44.        for (x=0; x<width; x+=1) {
  45.               t = (double) x / ((double) width);
  46.               y = offset - A * Math.sin (2 * Math.PI * f * t);
  47.               g.drawLine (x0, (int) y0, x, (int) y);
  48.               x0 = x;
  49.               y0 = y;
  50.        }
  51. }
  52. }
  53.