如何在 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)
所有這些方法都是靜態的,並返回一個 Font 物件。要設定字型,您需要使用這些方法之一建立字型物件,然後使用 **setText()** 方法將建立的字型設定到文字。
建立自定義字型
此外,您還可以使用 **loadFont()** 方法載入自己的字型。此方法有兩個變體:
一種方法接受 InputStream 類的物件(表示所需的字型)和一個表示大小的雙精度變數作為引數。
一種方法接受一個表示字型 URL 的字串變數和一個表示大小的雙精度變數作為引數。
要載入自定義字型:
在您的專案資料夾中建立一個名為 resources/fonts 的目錄。
下載所需的字型並將檔案放置在上面建立的資料夾中。
使用 **loadFont()** 方法載入字型。
透過例項化 **javafx.scene.text.Text** 類來建立文字節點。
使用 **setText()** 方法將字型設定到文字。
示例
import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.DropShadow; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.Text; public class CustomFontExample extends Application { public void start(Stage stage) throws FileNotFoundException { //Creating a text object Text text = new Text(30.0, 75.0, "ట్యూ టోరియల్స్ పాయింట్ కి స్వా గతిం"); //Loading a font from local file system Font font = Font.loadFont("file:resources/fonts/TenaliRamakrishna-Regular.ttf", 45); //Setting the font text.setFont(font); //Setting color of the text text.setFill(Color.BROWN); text.setStroke(Color.BLUEVIOLET); text.setStrokeWidth(0.5); //Creating the inner shadow effect //Creating the drop shadow effect DropShadow shadow = new DropShadow(); shadow.setOffsetY(5.0); //Setting the effect to the text text.setEffect(shadow); //Setting the stage Group root = new Group(text); Scene scene = new Scene(root, 595, 150, Color.BEIGE); stage.setTitle("Custom Font"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
輸出
廣告