JavaFX - 填充動畫



在本教程的色彩部分,我們學習了 JavaFX 節點可以使用各種顏色著色。但是,我們只學習了使用 `setFill()` 方法為物件著色;我們也可以使用動畫來更改形狀的填充顏色。這種型別的動畫稱為填充動畫。

填充動畫是一種在指定時間段內更改 JavaFX 節點顏色的動畫。這種動畫通常用於應用程式中進行測驗:如果答案正確,選項將變為“綠色”,否則變為“紅色”。

填充動畫

填充動畫是使用屬於 `javafx.animation` 包的 `**FillTransition**` 類對 JavaFX 節點執行的。此類包含可用於設定物件動畫的各種屬性。

  • **duration** - 此填充動畫的持續時間。

  • **shape** - 此填充動畫的目標形狀。

  • **fromValue** - 指定此填充動畫的起始顏色值。

  • **toValue** - 指定此填充動畫的結束顏色值。

示例

以下是演示 JavaFX 中填充動畫的程式。將此程式碼儲存在名為 `**FillTransitionExample.java**` 的檔案中。

import javafx.animation.FillTransition; 
import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Circle; 
import javafx.stage.Stage; 
import javafx.util.Duration; 
         
public class FillTransitionExample extends Application { 
   @Override 
   public void start(Stage stage) {      
      //Drawing a Circle 
      Circle circle = new Circle(); 
      
      //Setting the position of the circle 
      circle.setCenterX(300.0f); 
      circle.setCenterY(135.0f); 
      
      //Setting the radius of the circle 
      circle.setRadius(100.0f); 
      
      //Setting the color of the circle 
      circle.setFill(Color.BROWN); 
      
      //Setting the stroke width of the circle 
      circle.setStrokeWidth(20); 
       
      //Creating the fill Transition 
      FillTransition fillTransition = new FillTransition(Duration.millis(1000)); 
      
      //Setting the shape for Transition 
      fillTransition.setShape(circle); 
      
      //Setting the from value of the transition (color) 
      fillTransition.setFromValue(Color.BLUEVIOLET);  
      
      //Setting the toValue of the transition (color) 
      fillTransition.setToValue(Color.CORAL); 
      
      //Setting the cycle count for the transition 
      fillTransition.setCycleCount(50); 
      
      //Setting auto reverse value to false 
      fillTransition.setAutoReverse(false);  
      
      //Playing the animation 
      fillTransition.play(); 
         
      //Creating a Group object  
      Group root = new Group(circle); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);   
      
      //Setting title to the Stage
      stage.setTitle("Fill transition example"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   }      
   public static void main(String args[]){ 
      launch(args); 
   } 
}

使用以下命令從命令提示符編譯並執行儲存的 java 檔案。

javac --module-path %PATH_TO_FX% --add-modules javafx.controls FillTransitionExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls FillTransitionExample

輸出

執行後,上述程式將生成如下所示的 JavaFX 視窗。

Fill Transition
廣告