import java.awt.*; import java.applet.*; import java.util.Random; /** * This class draws random points in and around a circle. */ public class Monte4 extends Applet { private static Random randy; private int NUM_POINTS; private int SIZE; private Image offScreenImage; private Graphics offScreenGraphics; private Label insideLabel; private TextField insideField; private Label outsideLabel; private TextField outsideField; private int randomInRange(int low, int high) { return (Math.abs(randy.nextInt()) % (high-low+1)) + low; } private double distance(int x1, int y1, int x2, int y2) { return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)); } public void init() { randy = new Random(); NUM_POINTS = Integer.parseInt(getParameter("points")); Dimension dim = getSize(); SIZE = dim.width; setLayout(new BorderLayout()); Panel p = new Panel(); insideLabel = new Label("Inside:"); p.add(insideLabel); insideField = new TextField(5); p.add(insideField); outsideLabel = new Label("Outside:"); p.add(outsideLabel); outsideField = new TextField(5); p.add(outsideField); add(p, BorderLayout.SOUTH); } public void paint(Graphics g) { if (offScreenImage == null) { insideField.setText("0"); outsideField.setText("0"); offScreenImage = createImage(SIZE, SIZE); offScreenGraphics = offScreenImage.getGraphics(); offScreenGraphics.setColor(Color.red); g.setColor(Color.red); offScreenGraphics.fillOval(0, 0, SIZE, SIZE); g.fillOval(0, 0, SIZE, SIZE); for (int i = 0; i < NUM_POINTS; i++) { int x = randomInRange(0, SIZE); int y = randomInRange(0, SIZE); if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) { offScreenGraphics.setColor(Color.white); g.setColor(Color.white); int value = Integer.parseInt(insideField.getText())+1; insideField.setText(""+value); } else { offScreenGraphics.setColor(Color.black); g.setColor(Color.black); int value = Integer.parseInt(outsideField.getText())+1; outsideField.setText(""+value); } offScreenGraphics.drawLine(x, y, x, y); g.drawLine(x, y, x, y); } } else { g.drawImage(offScreenImage, 0, 0, null); } } }