Dynamically change the color of a Rectangle in Javafx


Question

I am creating a two javafx.scene.shape.Rectangle objects in a GridPane and doing the following.

rectArray = new Rectangle[2];

boardGrid.setStyle("-fx-background-color: #C0C0C0;");

rectArray[0] = new Rectangle(12,12);
rectArray[0].setFill(Color.AQUA);
boardGrid.add(rectArray[0], 2, 0);

rectArray[1] = new Rectangle(12,12);
rectArray[1].setFill(Color.BLACK);
boardGrid.add(rectArray[1], 2, 1);       

Button buttonStart = new Button("Change color");
buttonStart.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
       @Override
       public void handle(MouseEvent event) {
          rectArray[0].setFill(Color.RED);
          try {
               Thread.sleep(2000);
          } 
          catch (InterruptedException e) {
               e.printStackTrace();
          }
          rectArray[1].setFill(Color.AZURE);
       }
});
boardGrid.add(buttonStart, 3, 1);
initializeScene(primaryStage, boardGrid);
...

When I run the code I am able to see two rectangles (One in Aqua and one in black) and when I click the button, I will have to wait for the 2 seconds to view the change in colors of both rectangles.

I change the color of one rectangle before Thread.sleep(2000) is called and then I change the color of the next rectangle.

My question is why am I supposed to wait for 2 seconds? Is there a way that I can dynamically update the colors of the rectangle?

1
0
9/22/2013 6:23:52 AM

Accepted Answer

You are sleeping on the UI thread which blocks any further processing (including refreshing the screen).

If you need to delay some code you can use a PauseTransition to wait for two seconds and use its onFinished method to run the rest of your code after the wait.

1
9/22/2013 7:49:15 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon