如何制作 java中画n(输入值)个大小位置都为随机的圆?1
发布网友
发布时间:2023-11-22 23:35
我来回答
共1个回答
热心网友
时间:2024-01-11 17:12
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;
JFrame jf = new JFrame("我的测试");
jf.add(new RandomCircleComponent(circlesNumber) );
jf.setSize(500,500);
jf.setVisible(true);
}
}