如何在 JavaFX 中将文本设置为粗体和斜体?
javafxobject oriented programmingprogramming更新于 2025/4/14 18:37:17
您可以使用 setFont() 方法将所需的字体设置为 JavaFX 中的文本节点。此方法接受 javafx.scene.text.Font 类的对象。
Font 类表示 JavaFX 中的字体,该类提供了名为 font() 方法的几种变体,如下所示 −
font(double size) font(String family) font(String family, double size) font(String family, FontPosture pose, double size) font(String family, FontWeight weight, double size) font(String family, FontWeight weight, FontPosture pose, 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 作为值。参数姿势。
示例
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 { //创建文本对象 String str = "Welcome to Tutorialspoint"; Text text = new Text(30.0, 80.0, str); //设置字体粗体和斜体 Font font = Font.font("Verdana", FontWeight.BOLD, FontPosture.ITALIC, 35); text.setFont(font); //设置文本颜色 text.setFill(Color.DARKCYAN); //设置舞台 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); } }