我在javafx.scene.shape.Rectangle
中创建了两个GridPane
个对象并执行了以下操作。
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秒?有没有办法可以动态更新矩形的颜色?
答案 0 :(得分:1)
你正在UI线程上睡觉,阻止任何进一步处理(包括刷新屏幕)。
如果您需要延迟某些代码,可以使用PauseTransition等待两秒钟并使用其onFinished
方法在等待后运行其余代码。