import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class PiEstimate extends JPanel implements ActionListener { private int tries, hits; public static final int SIZE = 400; public PiEstimate() { tries = 0; hits = 0; Timer clock = new Timer(10, this); clock.start(); } public void paintComponent(Graphics g) { int x = (int)(SIZE*Math.random() ); int y = (int)(SIZE*Math.random() ); tries++; int r = SIZE/2; g.setColor(Color.BLACK); g.drawOval(0,0, SIZE, SIZE); g.drawString( "Hits: "+ hits + " Tries: " + tries, r/2, r); double pi = 4.0* (double)hits/(double)(tries); g.drawString( "PI is about: "+ pi , r/2, r+20); if( (x-r)*(x-r) + (y-r)*(y-r) <= r*r) { hits++; g.setColor(Color.RED); } g.fillOval(x,y, 10, 10 ); } public void actionPerformed(ActionEvent e) { repaint(); } public static void main(String args) { JFrame w = new JFrame("Estimate Pi"); w.setSize(SIZE, SIZE+20); Container c = w.getContentPane(); c.add(new PiEstimate()); w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); w.setResizable(false); w.setVisible(true); } }