import javax.swing.JPanel; import java.awt.*; import java.util.Random; public class PiSquare extends JPanel { public PiSquare() { setBackground(Color.black); setPreferredSize(new Dimension(300,300)); } public void paintComponent(Graphics page) { super.paintComponent(page); // paints the background and sets the window size page.setColor(Color.white); Random point = new Random(); int i = 0; int n = 10000; // set the number of random points int inside = 0; double x, y; // Coordinates of a random point do { i++; x = point.nextDouble()*2-1; // Generate a random point y = point.nextDouble()*2-1; if (x*x + y*y <= 1) { inside++; // if inside the unit circle increment counter page.setColor(Color.white); } else page.setColor(Color.blue); page.fillRect ((int)(x*100)+150, (int)(y*100)+150, 1, 1); } while (i < n); page.drawString ("Pi = " + String.valueOf (4*(float)inside/n), 50, 270); } }