//  File: Polys.java - Demonstrate Polylines and Polygons
//                     Demonstrate Animation-in-Time

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.Timer;

public class Polys extends Applet {
    
    /**
    * Set up the background and the timer; start the timer
    */
    public void init() {
        setBackground(Color.black);
        timer = new Timer(DELAY, new PolyActionListener());
        timer.start();
    }

    /**
    * Retrieve applet's current width and height
    * Calculate new radius; calculate new points
    * Draw a polyline and a polygon
    */
    public void paint(Graphics g) {
        nWidth  = getSize().width;
        nHeight = getSize().height;
        dRadius = Math.min(nWidth, nHeight) / 2;
        g.setColor(Color.white);
        g.drawString(nPoints + " points", 10, 20);

        calculateNpoints(nPoints, dRadius, 0);
        g.drawPolyline(x, y, nPoints);

        calculateNpoints(nPoints, 4 * dRadius / 5, 1);
        drawPolygon(g, x, y, nPoints);

        showStatus(" Resize this applet while it is running...");
    }

    /**
    * Create x,y arrays; calculate points
    */
    private void calculateNpoints(final int n, final double dRadius2, final int nOffset) {
        x = new int[n + 1];
        y = new int[n + 1];
        if (nOffset > 0) {
            x[0] = nWidth  / 2;
            y[0] = nHeight / 2;
        }
        for (int i = 0; i < n; i++) {
            x[i + nOffset] = (int) (dRadius2 * Math.cos(i * dDelta) + nWidth  / 2);
            y[i + nOffset] = (int) (dRadius2 * Math.sin(i * dDelta) + nHeight / 2);
        }
    }

    /**
    * Convert degrees to radians
    */
    private double toRadians(double dDegrees) {
        return (dDegrees * Math.PI) / 180.0;
    }

    /**
    * Draw a polygon based on the current x,y point arrays
    */
    private void drawPolygon(Graphics g, final int[] x, final int[] y, final int nPoints) {
        g.setColor(new Color(0, 28 * nPoints, 255 - 28 * nPoints));
        g.fillPolygon(x, y, nPoints + 1);
    }
    
    /**
    * Implements the action listener for the Timer
    */
    private class PolyActionListener implements ActionListener {

        /**
        * Updates the position of the image and possibly the direction
        * of movement whenever the timer fires an action event
        */
        public void actionPerformed(ActionEvent event) {
            nPoints = (nPoints + 1) % 10;
            if (nPoints < 2)
                nPoints = 2;
            repaint();
        }
    }

    private double dRadius;
    private double dDelta = toRadians(45);
    private int nWidth, nHeight;

    private int[] x;
    private int[] y;
    private int nPoints = 2;

    private Timer timer;
    private final int DELAY = 1000;
}
