Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Random Circles

843789May 12 2010 — edited May 12 2010
Hey,

I am trying to make a program that asks a user for input. In this case the program will ask the user how many circles (up to 20) the user wants the program to draw. After that (depending how many circles) the program will draw that many circles and give them a random color. As of now I have that, but the only problem I have is that no matter what number I put in...the program will draw its own amount of circles. If I want it to draw 5, 12, or 20 circles it will ignore it and just draw its own amount. Hope this can be resolved I spent a good amount of time and it is rather annoying lol.

Component:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import java.util.Random;
import java.awt.geom.Ellipse2D;
import java.awt.Color;
import java.util.*;

/**
A component that draws two rectangles.
*/
public class RandomCircleComponent extends JComponent
{
public void paintComponent(Graphics g)
{


// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;

// Construct a rectangle and draw it
generator = new Random();
Color myColor = new Color(generator.nextInt(256),generator.nextInt(256),generator.nextInt(256));

// final int TRIES = 20;
for (int i = 1; i <= 100; i++)
{

num1 = generator.nextInt(300);
num2 = generator.nextInt(300);
Ellipse2D.Double circle = new Ellipse2D.Double(num1, num2, 20, 30);

g2.setColor(myColor);
g2.draw(circle);
g2.fill(circle);

}
}

int num1 = 1;
int num2 = 2;
private Random generator;
}

Viewer:

import javax.swing.*;
import java.util.Scanner;

public class RandomCircleViewer
{
public static void main(String[] args)
{


Scanner in = new Scanner(System.in);
System.out.println("Enter the number of circles you wish to draw");
System.out.print("(Please enter an integer between 1 and 20)");
int i = in.nextInt();




JFrame frame = new JFrame();
frame.setSize(450, 475);
frame.setTitle("CIRCLES!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RandomCircleComponent component = new RandomCircleComponent();
frame.add(component);
frame.setVisible(true);
}
}

I asked for help before on the forums and I was really pleased, hopefully I can receive help again.

Thanks again.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 9 2010
Added on May 12 2010
10 comments
703 views