编写一个JavaFX程序,显示10000个非常小的圆(半径为1像素),使它们位于可视区域内的随机位置。将场景左半部分用红点填充,右半部分用绿点填充。使用场景的getWidth方法,判断场景的左右中心点。
实验过程
1. 结构目录
2. 实验代码
package tech.zger.www;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.util.Random;
/**
* @author zg
* @create 2021/11/16 10:19
*/
public class MainApplication extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("10000个圆");
primaryStage.setResizable(false);
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/tech/zger/www/logo/zg.jpg")));
Button button = new Button("显示");
button.setLayoutX(275);
button.setLayoutY(360);
Pane pane = new Pane();
pane.getChildren().add(button);
Scene scene = new Scene(pane, 600, 400);
primaryStage.setScene(scene);
button.setOnAction(event -> {
button.setVisible(false);
showCircles(primaryStage, pane);
});
primaryStage.show();
}
/**
* 生成10000个圆
*
* @param stage 主舞台
* @param pane 容器
*/
private void showCircles(Stage stage, Pane pane) {
int count = 10000;
Random random = new Random();
while (count > 0) {
// 获取可视化区域内的随机横坐标
int x = random.nextInt((int) (stage.getWidth() - 2)) + 1;
// 获取可视化区域内的随机纵坐标
int y = random.nextInt((int) (stage.getHeight() - 2)) + 1;
Circle circle = new Circle();
// 设置圆心位置
circle.setCenterX(x);
circle.setCenterY(y);
// 设置圆的半径为1
circle.setRadius(1);
// 将场景左半部分用红点填充,右半部分用绿点填充
if (x > stage.getWidth() / 2) {
circle.setFill(Color.GREEN);
} else {
circle.setFill(Color.RED);
}
pane.getChildren().add(circle);
count--;
}
}
}
3. 效果展示
- 初始界面
- 点击显示后