I want to add a sequence of points into a canvas. But the outcome is showing all points at the same time. Here is my code:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Random;
public class BasicOpsTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Drawing Operations Test");
Group root = new Group();
Canvas canvas = new Canvas(300, 250);
GraphicsContext gc = canvas.getGraphicsContext2D();
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
drawShapes(gc);
}
private void drawShapes(GraphicsContext gc) {
gc.setFill(Color.GREEN);
gc.setStroke(Color.BLUE);
Random rand = new Random();
for (int i = 0; i < 200; i++) {
gc.fillOval(rand.nextDouble() * 300, rand.nextDouble() * 250, 2, 2);
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I want to see the outcome adding each point successively. How can I do?
///////////
My solution using AnimationTimer
is:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.animation.AnimationTimer;
import java.util.Random;
public class BasicOpsTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Drawing Operations Test");
Group root = new Group();
Canvas canvas = new Canvas(300, 250);
GraphicsContext gc = canvas.getGraphicsContext2D();
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
drawShapes(gc);
}
private void drawShapes(GraphicsContext gc) {
Random rand = new Random();
gc.setFill(Color.GREEN);
AnimationTimer at = new AnimationTimer() {
public void handle(long now) {
gc.fillOval(rand.nextDouble() * 300, rand.nextDouble() * 250, 2, 2);
}
};
at.start();
}
}
That resolve my problem!