Java编写小程序随机显示出13个颜色的彩色圆形和矩形
时间: 2024-10-16 08:11:14 浏览: 19
在Java中,我们可以利用Swing库创建一个图形界面程序,展示彩色圆形和矩形。这里是一个简单的示例,使用Random类生成随机颜色,并设置形状的颜色:
```java
import java.awt.*;
import javax.swing.*;
public class ColorShapeExample extends JFrame {
private static final int SHAPE_COUNT = 13;
private Random random;
public ColorShapeExample() {
// 初始化随机数生成器
random = new Random();
// 设置窗口的基本属性
setTitle("Random Colored Shapes");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 添加绘图组件
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < SHAPE_COUNT; i++) {
int x = random.nextInt(getWidth());
int y = random.nextInt(getHeight());
int radius = random.nextInt(50) + 20;
Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
// 绘制圆形
g.setColor(color);
g.fillOval(x, y, radius * 2, radius * 2);
// 可能绘制矩形
if (random.nextBoolean()) {
int rectWidth = random.nextInt(radius * 2) + 40;
int rectHeight = random.nextInt(radius * 2) + 40;
g.fillRect(x, y, rectWidth, rectHeight);
}
}
}
};
setContentPane(panel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ColorShapeExample();
}
});
}
}
阅读全文