用Java绘制颜色随机的圆圈
时间: 2024-05-15 17:16:21 浏览: 8
下面是一个用Java绘制颜色随机的圆圈的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class RandomCircle extends JPanel {
private static final int CIRCLE_COUNT = 20;
private static final int MIN_RADIUS = 10;
private static final int MAX_RADIUS = 50;
private final Random random = new Random();
private Color getRandomColor() {
return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < CIRCLE_COUNT; i++) {
int x = random.nextInt(getWidth() - MAX_RADIUS * 2) + MAX_RADIUS;
int y = random.nextInt(getHeight() - MAX_RADIUS * 2) + MAX_RADIUS;
int radius = random.nextInt(MAX_RADIUS - MIN_RADIUS + 1) + MIN_RADIUS;
Color color = getRandomColor();
g.setColor(color);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Random Circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RandomCircle panel = new RandomCircle();
panel.setPreferredSize(new Dimension(500, 500));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
```
这个代码创建了一个`RandomCircle`类,继承自`JPanel`,覆盖了`paintComponent`方法,在其中绘制了多个随机颜色和半径的圆。`getRandomColor`方法用于生成随机颜色,`paintComponent`方法则用于循环生成一定数量的圆,每个圆的位置、半径和颜色都是随机的。最后,在`main`方法中创建一个`JFrame`,将`RandomCircle`添加到其中,并显示出来。