动态更改Javafx中Rectangle的颜色 [英] Dynamically change the color of a Rectangle in Javafx

查看:2023
本文介绍了动态更改Javafx中Rectangle的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 GridPane 中创建了两个 javafx.scene.shape.Rectangle 对象并执行以下操作。

I am creating a two javafx.scene.shape.Rectangle objects in a GridPane and doing the following.

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秒钟来查看两个矩形的颜色变化。

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.

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

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

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

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?

推荐答案

你正在睡觉的UI线程阻止任何进一步处理(包括刷新屏幕)。

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

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

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.

这篇关于动态更改Javafx中Rectangle的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆