如何在 JavaFX 中使文字加粗和斜體?


您可以使用 **setFont()** 方法將所需的字型設定到 JavaFX 中的文字節點。此方法接受 **javafx.scene.text.Font** 類的物件。

**Font** 類表示 JavaFX 中的字型,此類提供名為 **font()** 方法的幾個變體,如下所示:

font(double size)
font(String family)
font(String family, double size)
font(String family, FontPosture posture, double size)
font(String family, FontWeight weight, double size)
font(String family, FontWeight weight, FontPosture posture, double size)

其中:

  • **size** (double) 表示字型的尺寸。

  • **family** (string) 表示要應用於文字的字型的族名。您可以使用 *getFamilies()* 方法獲取已安裝字型族的名稱。

  • **weight** 表示字型的粗細(*FontWeight* 列舉的常量之一:BLACK,BOLD,EXTRA_BOLD,EXTRA_LIGHT,LIGHT,MEDIUM,NORMAL,SEMI_BOLD,THIN)。

  • **posture** 表示字型的樣式(*FontPosture* 列舉的常量之一:REGULAR,ITALIC)。

要使文字加粗,請使用 **FontWeight.BOLD** 或 **FontWeight.EXTRA_BOLD** 作為引數 weight 的值;要使文字斜體,請使用 **FontPosture.ITALIC** 作為引數 posture 的值。

示例

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 Bold_Italic 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 bold and italic
      Font font = Font.font("Verdana", FontWeight.BOLD, FontPosture.ITALIC, 35);
      text.setFont(font);
      //Setting the color of the text
      text.setFill(Color.DARKCYAN);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Bold And Italic");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於:2020年5月16日

14K+ 瀏覽量

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告