Dynamically change the color of a Rectangle in Javafx


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);
boardGrid.add(rectArray[0], 2, 0);

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

Button buttonStart = new Button("Change color");
buttonStart.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
       public void handle(MouseEvent event) {
          try {
          catch (InterruptedException e) {
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?

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.

9/22/2013 7:49:15 AM

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