在 Javafx 中动态更改矩形的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18941011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:42:04  来源:igfitidea点击:

Dynamically change the color of a Rectangle in Javafx

javajavafxjava-8

提问by Wizard

I am creating a two javafx.scene.shape.Rectangleobjects in a GridPaneand doing the following.

javafx.scene.shape.Rectangle在 a 中创建了两个对象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);
...

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.

当我运行代码时,我能够看到两个矩形(一个是浅绿色,一个是黑色),当我单击按钮时,我将不得不等待 2 秒钟才能查看两个矩形的颜色变化。

I change the color of one rectangle before Thread.sleep(2000)is called and then I change the color of the next rectangle.

我在Thread.sleep(2000)调用之前更改了一个矩形的颜色,然后更改了下一个矩形的颜色。

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?

我的问题是为什么我应该等待 2 秒?有没有办法可以动态更新矩形的颜色?

采纳答案by assylias

You are sleeping on the UI thread which blocks any further processing (including refreshing the screen).

您正在阻止任何进一步处理(包括刷新屏幕)的 UI 线程上休眠。

If you need to delay some code you can use a PauseTransitionto wait for two seconds and use its onFinishedmethod to run the rest of your code after the wait.

如果您需要延迟某些代码,您可以使用PauseTransition等待两秒钟,并onFinished在等待后使用其方法运行其余代码。