Skip to content

Instantly share code, notes, and snippets.

@skrb
Created June 6, 2019 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skrb/60976269414fadb61ad0eadfe0cc5840 to your computer and use it in GitHub Desktop.
Save skrb/60976269414fadb61ad0eadfe0cc5840 to your computer and use it in GitHub Desktop.
AnimationTimerのサンプル
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class AnimationDemo extends Application {
private long previous = 0;
private final Random random = new Random();
private static final double WIDTH = 600;
private static final double HEIGHT = 400;
@Override
public void start(Stage stage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, WIDTH, HEIGHT);
scene.setFill(Color.BLACK);
stage.setScene(scene);
stage.show();
startAnimation(root);
}
private void startAnimation(Pane root) {
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long t) {
if (previous == 0) {
previous = t;
}
// 適当なタイミングで四角を生成
if (random.nextDouble() < 0.02) {
Rectangle rect = new Rectangle(WIDTH, random.nextDouble() * HEIGHT, 20, 20);
rect.setFill(Color.WHITE);
root.getChildren().add(rect);
}
// 四角を移動
// 左側まで移動したら削除候補とする
List<Node> removedRects
= root.getChildren().stream()
.map(node -> (Rectangle) node)
.map(rect -> {
double x = rect.getX();
x -= (t - previous) / 10_000_000.0;
rect.setX(x);
double y = rect.getY();
y += random.nextDouble() * 2.0 - 1.0;
rect.setY(y);
return rect;
})
.filter(rect -> {
double x = rect.getX();
if (x < -WIDTH) {
return true;
} else {
return false;
}
})
.collect(Collectors.toList());
// 左まで移動した四角を削除
root.getChildren().removeAll(removedRects);
previous = t;
}
};
timer.start();
}
public static void main(String... args) {
launch(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment