// BuffonsNeedle.java

// Written by Julian Devlin, 8/97, for the text book
// "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell


import java.applet.Applet;
import java.awt.*;

public class BuffonsNeedle
	extends java.applet.Applet
{
	NeedleArea na;				// AWT elements
	Label message;
	Button go;
	TextField num;
	Label results;
		
	Panel graphArea;
	Panel controls;

	// Set up all controls and put them in the window
	public void init() {
		message = new Label("No. of needles =");	// Create controls
		go = new Button("Simulate");
		num = new TextField(4);
		results = new Label("Estimate of pi is          ");
		
		graphArea = new Panel();				// Set up window
		controls = new Panel();
		setLayout(new BorderLayout());
	
		controls.setLayout(new FlowLayout());
		controls.add(message);
		controls.add(num);
		controls.add(go);
		controls.add(results);
		
		na = new NeedleArea(0); // initialize display
		add("Center", na);
		add("South", controls);
	}
	
	// Does the simulation, creating two arrays to store game states, then passes them
	// to a SpikeGraph
	public void simulate() {
		int nn = 0;
		float area;
		try {
			nn = Integer.parseInt(num.getText().trim());	// Get user input
		}
		catch (Exception e) {
			num.setText("");
			validate();
		}
		
		remove(na);
		na = new NeedleArea(nn);			// Create new needle area
		add("Center", na);							// Put up the graph
		validate();
		float est = na.setPoints();
		results.setText("Estimate of pi is " + String.valueOf(est));
		validate();
	}
	
	// Watch for a click on the go button
	public boolean action(Event evt, Object arg) {
		if (evt.target instanceof Button) {
			if ((String)arg == "Simulate") {
				simulate();
			}
		}
		return true;
	}
	
	public Insets insets() {
    	return new Insets(15,15,15,15);
	}
}
