问题
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:
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.
来源:https://stackoverflow.com/questions/18941011/dynamically-change-the-color-of-a-rectangle-in-javafx