[英]Dynamically change the color of a Rectangle in Javafx
我正在GridPane
創建兩個javafx.scene.shape.Rectangle
對象,然后執行以下操作。
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秒? 有沒有一種方法可以動態更新矩形的顏色?
您正在UI線程上睡眠,該線程會阻止任何進一步的處理(包括刷新屏幕)。
如果需要延遲某些代碼,則可以使用PauseTransition等待兩秒鍾,並使用其onFinished
方法在等待后運行其余代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.