如何在 JavaFX 中為節點新增顏色?


使用 setFill()setStroke() 方法可以為 JavaFX 中的節點新增顏色。setFill() 方法為節點的表面區域新增顏色,而 setStroke() 方法為節點的邊界應用顏色。

這兩種方法都接受 javafx.scene.paint.Paint 類的一個物件作為引數。它是用於填充形狀和背景和顏色填充的色調和漸變的基礎類。

JavaFX 中的 javafx.scene.paint.Color 類是 Paint 的子類,它將 RGB 色彩空間中的所有顏色封裝在 (作為其屬性)。

要為幾何形狀或背景或形狀的筆觸應用顏色,需要透過傳入表示所需顏色的 Color 物件來呼叫相應的方法。

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
public class ColorExample extends Application {
   public void start(Stage stage) {
      //Drawing a circle
      Circle circle = new Circle(75.0f, 65.0f, 40.0f );
      //Drawing a Rectangle
      Rectangle rect = new Rectangle(150, 30, 100, 65);
      //Drawing an ellipse
      Ellipse ellipse = new Ellipse(330, 60, 60, 35);
      //Drawing Polygon
      Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
      //Color by name
      circle.setFill(Color.CHOCOLATE);
      circle.setStrokeWidth(5);
      circle.setStroke(Color.DARKRED);
      //Using RGB
      rect.setFill(Color.rgb(150, 0, 255));
      rect.setStrokeWidth(5);
      rect.setStroke(Color.DARKRED);
      //Using HSB
      ellipse.setFill(Color.hsb(50, 1, 1));
      ellipse.setStrokeWidth(5);
      ellipse.setStroke(Color.DARKRED);
      //Using web
      poly.setFill(Color.web("#E9967A"));
      poly.setStrokeWidth(5);
      poly.setStroke(Color.DARKRED);
      //Setting the stage
      Group root = new Group(circle, ellipse, rect, poly);
      Scene scene = new Scene(root, 600, 150);
      stage.setTitle("Setting Colors");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於: 16-5-2020

3K+ 瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.