import java.awt.*; public class MCSquareGraph extends Graph { Point[] randPts; JRandom myRand; public MCSquareGraph(float min, float max) { minX = min; maxX = max; minY = 0f; maxY = (float) Math.pow(max, 2); inset = 30; myRand = new JRandom(); randPts = new Point[0]; } public float setRandPts(int n) { // FIX MIN MAX int results = 0; float x, y; randPts = new Point[n]; Dimension d = size(); //getSize() in 1.1.1 w = d.width - 2 * inset; h = d.height - 2 * inset; if (maxX - minX != 0) scaleX = (float) w / (maxX - minX); // Total width / range // = number of pixels for each point if (maxY - minY != 0) // Simalarly for y scale scaleY = (float) h / (maxY - minY); for(int i = 0; i < n; i++) { x = myRand.nextFloat(minX, maxX); y = myRand.nextFloat(minY, maxY); randPts[i] = new Point(adjX(x), adjY(y)); if (y <= Math.pow(x, 2)) results++; } return Math.round(10000f * (float) results / (float) n * (maxX - minX) * (maxY - minY)) / 10000f; } // Determines size of this object, and scales the coordinates accordingly. public void setPoints() { Dimension d = size(); //getSize() in 1.1.1 w = d.width - 2 * inset; h = d.height - 2 * inset; length = w; xCoords = new Float[length]; // Set up arrays for x and y coordinates of data points yCoords = new Float[length]; for(int i = 0; i < length; i++) { xCoords[i] = new Float(minX + i * (float) (maxX - minX) / ((float) w - 1f)); yCoords[i] = new Float(Math.pow(xCoords[i].floatValue(), 2)); } pixels = new Point[length]; // Initialize array for actual points to be graphed if (maxX - minX != 0) scaleX = (float) w / (maxX - minX); // Total width / range // = number of pixels for each point if (maxY - minY != 0) // Simalarly for y scale scaleY = (float) h / (maxY - minY); int x, y; // current x and y coordinates for (int i = 0; i < length; i++) { // Calculate what the coordinates of each data point should be, then add a Point object to the array x = adjX(xCoords[i]); y = adjY(yCoords[i]); pixels[i] = new Point(x, y); } } public void paint(Graphics g) { Font f; String fName; FontMetrics fm; f = g.getFont(); fName = f.getName(); f = new Font(fName, Font.PLAIN, 9); g.setFont(f); fm = g.getFontMetrics(); setPoints(); // When we are ready to paint, the dimensions of the component have been setTicks(true, fm); // set, so we can calculate coordinates of all the points g.setColor(new Color(0, 0, 0)); for (int i = 0; i < length - 1; i++) { // For each point g.drawLine(pixels[i].x, pixels[i].y, pixels[i + 1].x, pixels[i + 1].y); // Connect it to the next point } // Draw the points for (int i = 0; i < randPts.length; i++) { g.drawOval(randPts[i].x, randPts[i].y, 2, 2); } drawXAxis(g); drawYAxis(g); g.setColor(new Color(150, 0, 0)); // Make ticks red drawTicks(g); g.setColor(new Color(0, 0, 100)); // Make labels blue labelTicks(g); g.setColor(new Color(0, 0, 0)); } }