0
我在GridPane
中創建了兩個javafx.scene.shape.Rectangle
對象,並執行以下操作。動態更改Javafx中矩形的顏色
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);
...
當我跑,我能看到兩個矩形(一個在Aqua和一個黑色),當我按一下按鈕,我將不得不等待2秒鐘,查看顏色改變的代碼兩個矩形。
在調用Thread.sleep(2000)
之前,我改變了一個矩形的顏色,然後改變了下一個矩形的顏色。
我的問題是爲什麼我要等待2秒?有沒有一種方法可以動態更新矩形的顏色?