Creating circles in javafx with thread.sleep()

时间:2016-04-29 20:19:35

标签: java javafx

I am trying to make program which will make new circles using javafx every three seconds. But when i run my loop with thread.sleep() my graphic window with circles appear when the loop is over. For example, i want to make 10 circles. My graphic window will appear when all 10 circles are made. But i want my graphic to appear when first circle is made. And on that window missing circles appear every three seconds.

@Override
    public void start(Stage primaryStage) throws Exception 
    {
        Pane pane = new Pane();
       //pane.setStyle("-fx-fill: linear-gradient(orange,orangered,blue);");
       pane.setPrefSize(1200,1000);
       pane.getChildren().add(new MyCircle().getCircle());
       for(int i=0; i<10; i++)
       {
           try
           {
               Thread.sleep(3000);
           }catch(InterruptedException e){}
            pane.getChildren().add(new MyCircle().getCircle());
        }   
        Form f = new Form("This is hello world", pane);
   }

I made Form class which have Scene, and also i made Circle class which give me my circles with location and style which i want. In this program above my gui appear when all the circles are made.

1 个答案:

答案 0 :(得分:2)

作为JavaFX的经验法则:每当你想使用Thread.sleep重新考虑你的设计时,因为它可能是错误的!

在您的特定情况下,有多种方法可以解决此问题。我个人会使用ScheduledThreadPoolExecutor。请注意在Platform.runLater调用中包装Circles的实际创建。

您还可以使用AnimationTimer来实现目标。