我想在画布上添加一系列点。但是结果同时显示了所有要点。这是我的代码:
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();
}
}
}
}
我希望看到结果逐个相加。我该怎么办?
////////////
我使用AnimationTimer
的解决方案是:
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();
}
}
那解决了我的问题!