简体   繁体   English

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

[英]Dynamically change the color of a Rectangle in Javafx

I am creating a two javafx.scene.shape.Rectangle objects in a GridPane and doing the following. 我正在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);
...

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. 运行代码时,我可以看到两个矩形(一个在Aqua中,一个在黑色中),当我单击按钮时,我将不得不等待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? 我的问题是为什么我应该等待2秒? Is there a way that I can dynamically update the colors of the rectangle? 有没有一种方法可以动态更新矩形的颜色?

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 PauseTransition to wait for two seconds and use its onFinished method to run the rest of your code after the wait. 如果需要延迟某些代码,则可以使用PauseTransition等待两秒钟,并使用其onFinished方法在等待后运行其余代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM