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秒?有没有一种方法可以动态更新矩形的颜色?