用javaFX写一个雨刷实例
时间: 2023-12-21 22:07:18 浏览: 80
用java写的代码雨
下面是一个简单的JavaFX雨刷实例:
```java
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
public class RainBrush extends Application {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int DROP_SIZE = 10;
private static final int SPEED = 5;
private GraphicsContext gc;
private Timeline timeline;
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = new Canvas(WIDTH, HEIGHT);
gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
StackPane root = new StackPane(canvas);
Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setScene(scene);
primaryStage.setTitle("Rain Brush");
primaryStage.show();
timeline = new Timeline(new KeyFrame(Duration.millis(SPEED), event -> draw()));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
private void draw() {
gc.clearRect(0, 0, WIDTH, HEIGHT);
for (int i = 0; i < WIDTH; i += DROP_SIZE) {
gc.fillRect(i, (int) (Math.random() * HEIGHT), DROP_SIZE, DROP_SIZE);
}
}
@Override
public void stop() throws Exception {
timeline.stop();
}
public static void main(String[] args) {
launch(args);
}
}
```
这个实例创建了一个800x600的画布,并在其中随机生成方块雨滴。使用Timeline和KeyFrame实现动画效果,通过清除画布并重新绘制雨滴来模拟雨刷的效果。您可以尝试调整DROP_SIZE和SPEED等变量来获得不同的效果。
阅读全文