如何制作 java中画n(输入值)个大小位置都为随机的圆?

来源:百度知道 编辑:UC知道 时间:2024/05/25 05:12:31
如题,期中n为输入值, 直径和圆心均为随机产生.
已知代码如下

import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;

/**
A RandomCircleComponent draws a number of random circles.
*/
public class RandomCircleComponent extends JComponent
{
/**
Constructs a RandomCircleComponent that draws a given number
of circles.
@param n the number of circles to draw.
*/
public RandomCircleComponent(int n)
{
. . .
}
public void paintComponent(Graphics g)
{
. . .
}
. . .
}

过几天马上考试了,这题还完全弄不明白,请高手解答,谢谢
呵呵还是有些问题:
1,我们暂时不让用g.drawOval画,老师给出的范围是必须用 Ellipse2D.Double circles = new Ellipse2D.Double();g2.draw(circle);
2, 这个code只能在public RandomCircleComponent(int n) ,public void paintComponent(Graphics g) 还有最后面的private添加东西,其他的地方不能添加新code.

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.JComponent;
import javax.swing.JFrame;

/**
* A RandomCircleComponent draws a number of random circles.
*/
public class RandomCircleComponent extends JComponent {
private Color[] colors = {Color.red,Color.green,Color.black,Color.yellow,Color.cyan,Color.blue,Color.darkGray};
private int n;
private Random random = new Random();
public RandomCircleComponent(int n) {
this.n = n;
}

public void paintComponent(Graphics g) {
for(int i=0;i<n;i++){
int x = Math.abs(random.nextInt()%300);
int y = Math.abs(random.nextInt()%300);
int width = Math.abs(random.nextInt()%300);
g.setColor(colors[ Math.abs(random.nextInt()%6)]);
g.drawOval(x, y, width, width);
}
}
public static void main(String[] args){
int circlesNumber = 100;