import java.awt.*; import java.applet.*; import java.util.Random; /** * This class draws random points in and around a circle. */ public class Monte3 extends Applet { private static Random randy; private int NUM_POINTS; private int SIZE; private Image offScreenImage; private Graphics offScreenGraphics; 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 = Math.min(dim.width, dim.height); } public void paint(Graphics g) { if (offScreenImage == null) { 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); } else { offScreenGraphics.setColor(Color.black); g.setColor(Color.black); } offScreenGraphics.drawLine(x, y, x, y); g.drawLine(x, y, x, y); } } else { g.drawImage(offScreenImage, 0, 0, null); } } }