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

回答

1

您正在UI线程中阻塞任何进一步处理(包括刷新屏幕)。

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