Hello,
The following program computes the value of Pi using the Hit/Miss method. Since I am doing all the drawing in the JPanel, I am not calling super.paintComponent(g). The program works well, but since I am not using the super.paintComponent, it does not draw the background. Is there any way to draw the background without using super.paintComponent(g)?
Thank you!
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.util.Scanner;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
public class estimatingPi extends JPanel implements Runnable
{
static int side, trials;
int countOut = 0, count = 0, countIn = 0;
private static BufferedImage image;
boolean flag = true;
private Thread thread;
private Graphics g;
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Monte Carlo - Estimating Pi\n---------------------------\n\nInput the size of the sides of the square");
side = s.nextInt();
System.out.println("Input the number of trials");
trials = s.nextInt();
estimatingPi pi = new estimatingPi();
JFrame p = new JFrame ("Hit and Miss - Estimating Pi");
p.add(pi);
p.setSize(500, 500);
p.setVisible(true);
}
public estimatingPi()
{
setBackground (Color.BLACK);
thread = new Thread (this);
thread.start();
}
public boolean checkPosition(double x, double y)
{
double cen = side/2;
if(Math.sqrt(Math.pow(cen-x, 2) + Math.pow(cen-y, 2)) > side/2)
return true;
else
return false;
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.CYAN);
g2.drawOval(0, 0, side, side);
g2.setColor(Color.RED);
g2.drawLine(0, side, side, side);
g2.drawLine(side, side, side, 0);
boolean in;
double x = Math.random() * side;
double y = Math.random() * side;
if(checkPosition(x, y))
{
g2.setColor(Color.RED);
Line2D.Double l = new Line2D.Double(x, y, x, y);
g2.draw(l);
countOut++;
}
else
{
g2.setColor(Color.BLUE);
Line2D.Double l = new Line2D.Double(x, y, x, y);
g2.draw(l);
countIn++;
}
count++;
}
public void run()
{
while (flag == true)
{
try
{
thread.sleep(10);
}
catch (InterruptedException e)
{}
if (count == trials)
{
System.out.println("Out: " + countOut + "\nIn: " + countIn);
double piEstimated = 4*((double)countIn/(double)trials);
System.out.println("Pi is estimated to be: " + piEstimated);
flag = false;
}
repaint();
}
}
}