////////////////////////////////////////////////////////////////////////////
// "Pi.java" - Demonstrates approximating Pi by computing the perimeter-
// to-diameter ratio of an <i>n</i>-sided polygon
//
// Author: Joe Ganley, pi.10.ganley@spamgourmet.com
////////////////////////////////////////////////////////////////////////////


// import the Java APIs; should I just import the ones I use?
import java.lang.*;
import java.awt.*;

// import the nGon class
import nGon;


// the main Pi applet class
public class Pi extends java.applet.Applet {

private int		sides;			// # sides currently
private nGon		gon;			// the polygon
private Panel		controls;		// for the slider & text
private Scrollbar	sb;			// the slider
private Label		nTxt, piTxt;		// the text for n and pi


// init() - set up the controls and initialize the first polygon
public void init() {
  sides = 2;
  gon = new nGon(sides, Math.min(size().width, size().height) * 0.45,
		 (double) size().width / 2.0,
		 (double) (size().height - 40) / 2.0);
  setLayout(new BorderLayout());
  controls = new Panel();
  controls.resize(new Dimension(size().width, 40));
  controls.setLayout(new BorderLayout());
  nTxt = new Label("n = XXX");
  controls.add("West", nTxt);
  piTxt = new Label("pi = X.XXXX");
  controls.add("East", piTxt);
  sb = new Scrollbar(Scrollbar.HORIZONTAL, sides, 5, 2, 28);
  controls.add("South", sb);
  add("South", controls);
} // init()


// paint(Graphics) - paint the polygon and update the text displays
public void paint(Graphics g) {
  String       	piStr;
  Color		saveColor;
  Polygon	drawPoly;

  g.clearRect(0, 0, size().width, size().height - 40);
  saveColor = g.getColor();
  g.setColor(Color.green);
  drawPoly = gon.getPolygon();
  g.fillPolygon(drawPoly);
  g.setColor(saveColor);
  g.drawPolygon(drawPoly);
  nTxt.setText("n = " + sides);
  piStr = "pi = " + (gon.getPerimeter() / (2.0 * gon.getRadius()));
  piTxt.setText(piStr);
} // paint(Graphics)


// updateSides() - get the slider value, update the polygon, and redraw
public boolean updateSides() {
  sides = sb.getValue();

  // (sloppily) implement log scale
  if ((sides >= 11) && (sides <= 19)) {
    sides = (sides - 9) * 10;
  }
  else if (sides >= 20) {
    sides = (sides - 18) * 100;
  }

  gon = new nGon(sides,	Math.min(size().width, size().height) * 0.45,
		 (double) size().width / 2.0,
		 (double) (size().height - 40) / 2.0);
  repaint();
  return(true);
} // updateSides()


// handleEvent(Event) - run an update if a scroll event happens; otherwise
// just pass it on through...
public boolean handleEvent(Event e) {
  switch (e.id) {
  case Event.SCROLL_LINE_UP: case Event.SCROLL_LINE_DOWN:
  case Event.SCROLL_PAGE_UP: case Event.SCROLL_PAGE_DOWN:
  case Event.SCROLL_ABSOLUTE: {
    updateSides();
    break;
  }
  default: {
    break;
  }
  } // switch

  return(false);
} // handleEvent(Event)

} // class Pi extends Java.applet.Applet
			


