javafx绘制彩色不相交的圆圈,个数从键盘上输入,半径在10-20之间,色彩随机
时间: 2024-05-12 13:19:22 浏览: 100
Java语言 画随机的圆
以下是一个实现示例:
```java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main extends Application {
private static final int MIN_RADIUS = 10;
private static final int MAX_RADIUS = 20;
private int circleCount;
private List<Circle> circles;
@Override
public void start(Stage primaryStage) throws Exception {
// 从键盘上输入圆圈的个数
Scanner scanner = new Scanner(System.in);
System.out.print("请输入圆圈个数:");
circleCount = scanner.nextInt();
// 创建圆圈
circles = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < circleCount; i++) {
double radius = MIN_RADIUS + random.nextDouble() * (MAX_RADIUS - MIN_RADIUS);
Color color = Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256));
Circle circle = new Circle(radius, color);
circles.add(circle);
}
// 布局圆圈
boolean intersect;
do {
intersect = false;
for (int i = 0; i < circleCount; i++) {
Circle circle1 = circles.get(i);
circle1.setCenterX(MIN_RADIUS + random.nextDouble() * (600 - 2 * MAX_RADIUS));
circle1.setCenterY(MIN_RADIUS + random.nextDouble() * (400 - 2 * MAX_RADIUS));
for (int j = i + 1; j < circleCount; j++) {
Circle circle2 = circles.get(j);
if (circle1.intersects(circle2.getBoundsInLocal())) {
intersect = true;
break;
}
}
if (intersect) {
break;
}
}
} while (intersect);
// 添加圆圈到面板
Pane root = new Pane();
root.getChildren().addAll(circles);
// 显示窗口
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
该示例中,首先从键盘上输入圆圈的个数,然后创建圆圈,并随机生成半径和色彩。接着,使用一个循环来布局圆圈,每次随机生成圆心坐标,并检查当前圆圈是否与其他圆圈相交。如果有相交,则需要重新生成圆心坐标,直到所有圆圈都不相交为止。最后,将所有圆圈添加到面板中,并显示窗口。
阅读全文