import java.awt.*; import java.applet.*; import java.awt.event.*; import java.util.Random; /** * This class draws random points in and around a circle. */ public class Monte5 extends Applet implements ActionListener { 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 Button dotButton; 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()); dotButton = new Button("Click to generate dots"); dotButton.addActionListener(this); add(dotButton, BorderLayout.SOUTH); drawCircle(); } public void drawCircle() { offScreenImage = createImage(SIZE, SIZE); offScreenGraphics = offScreenImage.getGraphics(); Graphics g = getGraphics(); offScreenGraphics.clearRect(0,0,SIZE,SIZE); g.clearRect(0,0,SIZE,SIZE); offScreenGraphics.setColor(Color.red); g.setColor(Color.red); offScreenGraphics.fillOval(0, 0, SIZE, SIZE); g.fillOval(0, 0, SIZE, SIZE); } public void drawDots() { drawCircle(); Graphics g = getGraphics(); 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); } } public void paint(Graphics g) { g.drawImage(offScreenImage, 0, 0, null); } public void actionPerformed(ActionEvent e) { if (e.getSource() == dotButton) { drawDots(); } } }