// BetrandsParadox2.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 BertrandsParadox2
	extends java.applet.Applet
{
	Float[] yCoords;		// Variables for simulation - on unit circle
	
	//Float[] abgX;
	//Float[] abgY;
	
	//AreaBarGraph abg;				// AWT elements
	BertBoard2 bb;
	Label message;
	Button go;
	TextField num;
	Label results;
	GridBagLayout gbl;
	GridBagConstraints cc;
		
	Panel graphArea;
	Panel controls;
	
	JRandom myRand;

	// Set up all controls and put them in the window
	public void init() {
		message = new Label("Number of chords =");	// Create controls
		go = new Button("Simulate");
		num = new TextField(4);
		results = new Label("Probability that chord is longer than sqrt(3):           ");
		
		graphArea = new Panel();				// Set up window
		controls = new Panel();
		setLayout(new BorderLayout(5, 5));
		
		add("South", controls);
		add("Center", graphArea);
		
		bb = new BertBoard2();
		graphArea.setLayout(new GridLayout(1, 1));
		graphArea.add(bb);
		
		gbl = new GridBagLayout();
		controls.setLayout(gbl);
		
		cc = new GridBagConstraints();
		
		cc.gridx = 0;
		cc.gridy = 0;
		gbl.setConstraints(message, cc);
		controls.add(message);
		
		cc.gridx = 1;
		gbl.setConstraints(num, cc);
		controls.add(num);
		
		cc.gridx = 2;
		gbl.setConstraints(go, cc);
		controls.add(go);
		
		cc.gridwidth = 3;
		cc.gridx = 0;
		cc.gridy = 11;
		gbl.setConstraints(results, cc);
		controls.add(results);
		
		myRand = new JRandom();
		
		//controls.resize(controls.getLayout().preferredLayoutSize(controls));
		validate();
	}
	
	
	// Does the simulation, creating two arrays to store game states, then passes them
	// to a AreaBarGraph
	public void simulate() {
		int n = 0;
		try {
			n = Integer.parseInt(num.getText().trim());		// Get user input
		}
		catch (Exception e) {
			num.setText("");
			validate();
		}
		yCoords = new Float[n];
		
		for (int i = 0; i < n; i++) {				// Do actual simulation
			yCoords[i] = new Float(myRand.nextFloat(-1, 1));
		}
		
		//graphArea.remove(abg);
		graphArea.remove(bb);
		//abg = new AreaBarGraph(abgX, abgY);	// Create new AreaBarGraph
		bb = new BertBoard2(yCoords);
		//graphArea.add(abg);
		graphArea.add(bb);							
		validate();
		float est = bb.setPoints();
		results.setText("Probability that chord is longer than sqrt(3): " 
			+ 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(5,5,5,5);
	}

}


