// GeometricPlot.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 GeometricPlot extends java.applet.Applet { Float[] xCoords; // Variables for simulation Float[] yCoords; SpikeGraph sg; // AWT elements Panel dispArea; Panel controls; // Panel for user controls Label numl; // Controls TextField num; Button go; GridBagLayout gbl; GridBagConstraints cc; // Initialize applet public void init() { numl = new Label("p ="); // Create controls num = new TextField(".5", 4); go = new Button("Go"); sg = new SpikeGraph(); // initialize a graphing space dispArea = new Panel(); // Set up window controls = new Panel(); setLayout(new BorderLayout(5, 5)); add("South", controls); add("Center", dispArea); dispArea.setLayout(new GridLayout(1, 1)); dispArea.add(sg); gbl = new GridBagLayout(); controls.setLayout(gbl); cc = new GridBagConstraints(); cc.gridx = 0; cc.gridy = 0; gbl.setConstraints(numl, cc); controls.add(numl); cc.gridx = 1; gbl.setConstraints(num, cc); controls.add(num); cc.gridx = 0; cc.gridy = 1; cc.gridwidth = 2; gbl.setConstraints(go, cc); controls.add(go); validate(); } // Handle events public boolean handleEvent(Event evt) { if (evt.target instanceof Button) { if (evt.target == go && evt.id == Event.ACTION_EVENT) // When button is clicked { simulate(Float.valueOf(num.getText()).floatValue()); return true; // Generate correct number of tosses } } return super.handleEvent(evt); // Handle other events as usual } // Calculate probabilities public void simulate(float prob) { float temp; float q = 1f - prob; xCoords = new Float[20 + 2]; // we add an extra point with y == 0 so that x labels yCoords = new Float[20 + 2]; // will be shown for sure - a stupid fakeout for (int i = 0; i <= 20; i++) { xCoords[i] = new Float(i); temp = (float) Math.pow((double) q, (double) i - 1) * prob; yCoords[i] = new Float(temp); } xCoords[21] = new Float(19.5f); yCoords[21] = new Float(0f); dispArea.remove(sg); sg = new SpikeGraph(xCoords, yCoords); // Create new SpikeGraph dispArea.add(sg); // Put up the graph validate(); } }