如何在 JavaFX 中為文字新增描邊和顏色?


由於 JavaFX 中的 **javafx.scene.text.Text** 類繼承自 Shape 類,因而它繼承了該類的所有成員。你可以透過為 Text 類繼承的描邊、描邊寬度和填充屬性設定值,來修改文字節點的描邊和顏色。

  • **描邊寬度** − 描邊寬度屬性指定/定義了形狀的邊框線的寬度。你可以使用 Shape 類的 **setWidth()** 方法,設定邊框線的寬度。

  • **填充** − 填充屬性指定/定義了用於填充形狀內部區域的顏色。你可以使用 Shape 類的 **fill()** 方法,使用所需顏色填充特定形狀。

  • **描邊** − 描邊屬性指定/定義了形狀邊框的顏色。你可以使用 javafx.scene.shape.Shape 類的 **setStroke()** 方法,設定邊框線顏色。

示例

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class SettingStroke_Color extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a text object
      String str = "Welcome to Tutorialspoint";
      Text text = new Text(30.0, 80.0, str);
      //Setting the font
      Font font = Font.font("Brush Script MT", FontWeight.BOLD, FontPosture.REGULAR, 65);
      text.setFont(font);
      //Setting the color of the text
      text.setFill(Color.BROWN);
      //Setting the width
      text.setStrokeWidth(2);
      //Setting the stroke color
      text.setStroke(Color.BLUE);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Stroke And Color");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於: 14-Apr-2020

2 千+ 次瀏覽

開啟您的 職業生涯

完成課程獲取認證

開始吧
廣告
© . All rights reserved.