0

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.

Miljan Rakita
  • 1,433
  • 4
  • 23
  • 44
  • I don't know javafx, but it sounds like you need to activate its event loop before every sleep. – totoro Apr 29 '16 at 20:57
  • 1
    You are calling `Thread.sleep` on the JavaFX UI thread, so it freezes, unable to update the display. I think these two questions should give you an idea of how it should be done: [Update UI from worker thread](http://stackoverflow.com/questions/20497845/constantly-update-ui-in-java-fx-worker-thread) and [Why thread blocks JavaFX UI updates](http://stackoverflow.com/questions/33112560/why-is-a-thread-blocking-my-javafx-ui-thread) – Itai Apr 29 '16 at 21:19

1 Answers1

2

As a rule of thumb for JavaFX: Whenever you are tempted to use Thread.sleep reconsider your design because it is probably wrong!

In your particular case there are various ways to solve this problem. I would personally use a ScheduledThreadPoolExecutor. Just take care to wrap the actual creation of the Circles in a Platform.runLater call.

You could also use an AnimationTimer to achieve your goal.

mipa
  • 10,369
  • 2
  • 16
  • 35