javafx实现汽车雨刷代码
时间: 2023-10-26 18:09:28 浏览: 94
以下是一个简单的JavaFX汽车雨刷代码示例:
```java
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CarWindshieldWiper extends Application {
private static final double WIDTH = 800;
private static final double HEIGHT = 600;
private static final double WIPER_WIDTH = 100;
private static final double WIPER_HEIGHT = 20;
private static final double RAINDROP_RADIUS = 3;
private Rectangle windshield;
private Rectangle wiper;
private Group rainGroup;
@Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
// 创建风挡和雨刷
windshield = new Rectangle(0, 0, WIDTH, HEIGHT);
windshield.setFill(Color.LIGHTGRAY);
wiper = new Rectangle(WIDTH / 2 - WIPER_WIDTH / 2, HEIGHT / 2 - WIPER_HEIGHT / 2, WIPER_WIDTH, WIPER_HEIGHT);
wiper.setFill(Color.DARKGRAY);
root.getChildren().addAll(windshield, wiper);
// 创建雨滴
rainGroup = new Group();
for (int i = 0; i < 50; i++) {
Circle raindrop = new Circle(Math.random() * WIDTH, Math.random() * HEIGHT, RAINDROP_RADIUS);
raindrop.setFill(Color.BLUE);
rainGroup.getChildren().add(raindrop);
}
root.getChildren().add(rainGroup);
// 创建动画
Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
KeyValue keyValue = new KeyValue(wiper.xProperty(), WIDTH / 2 + WIPER_HEIGHT / 2);
KeyFrame keyFrame = new KeyFrame(Duration.seconds(2), keyValue);
timeline.getKeyFrames().add(keyFrame);
timeline.setAutoReverse(true);
timeline.play();
// 雨滴动画
Timeline rainTimeline = new Timeline();
rainTimeline.setCycleCount(Timeline.INDEFINITE);
for (int i = 0; i < rainGroup.getChildren().size(); i++) {
Circle raindrop = (Circle) rainGroup.getChildren().get(i);
KeyValue kv = new KeyValue(raindrop.centerYProperty(), HEIGHT + RAINDROP_RADIUS);
KeyFrame kf = new KeyFrame(Duration.seconds(Math.random() * 2), kv);
rainTimeline.getKeyFrames().add(kf);
}
rainTimeline.play();
Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
这个示例创建了一个带有风挡和雨刷的汽车场景,并使用JavaFX的动画API模拟雨刷和雨滴的运动。
阅读全文