如何在 JavaFX 中创建文本流布局?

javafxobject oriented programmingprogramming更新于 2026/1/8 8:44:17

为了在我们的应用程序中创建富文本内容,JavaFX 提供了一种特殊的布局,称为文本流,由 javafx.scene.layout.TextFlow 类表示。使用此功能,您可以在单个文本流中布局多个文本节点。

由于它们是单独的节点,因此可以为它们设置不同的字体。如果您尝试将文本以外的节点添加到此布局,它们将被视为嵌入对象,并简单地插入文本之间。

此类有两个属性 −

  • lineSpacing − 此属性(双精度)用于指定文本对象之间的间距。您可以使用 setLineSpacing() 方法为此属性设置值。

  • textAlignment −此属性用于指定窗格中文本对象的对齐方式。您可以使用 setTextAlignment() 方法设置此属性的值。您可以向此方法传递四个值:CENTER、JUSTIFY、LEFT、RIGHT。

示例

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.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
public class TextFlowExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //创建文本对象
      Text text1 = new Text(30.0, 110.0, "Hi ");
      //设置字体
      Font font1 = Font.font("Brush Script MT", FontWeight.BOLD, 75);
      text1.setFont(font1);
      //设置文本颜色
      text1.setFill(Color.CORAL);
      text1.setStrokeWidth(1);
      text1.setStroke(Color.CHOCOLATE);
      Text text2 = new Text(40.0, 110.0, "Welcome To");
      Font font2 = Font.font("Verdana", FontWeight.LIGHT, 25);
      text2.setFont(font2);
      //设置文本颜色
      text2.setFill(Color.YELLOWGREEN);
      text2.setStrokeWidth(1);
      text2.setStroke(Color.DARKRED);
      Text text3= new Text(50.0, 110.0, "Tutorialspoint");
      Font font3 = Font.font("Kunstler Script", FontWeight.BOLD, 80);
      text3.setFont(font3);
      //设置文本颜色
      text3.setFill(Color.CORNFLOWERBLUE);
      text3.setStrokeWidth(1);
      text3.setStroke(Color.CRIMSON);
      Text text4 = new Text(" We provide free tutorials for readers in various technologies ");
      text4.setFont(new Font("Algerian", 30));
      text4.setFill(Color.DARKGOLDENROD);
      Text text5 = new Text("We believe in easy learning");
      //为文本设置字体
      text5.setFont(new Font("Ink Free",30));
      text5.setFill(Color.MEDIUMVIOLETRED);
      //创建文本流
      TextFlow textFlow = new TextFlow();
      textFlow.setPrefWidth(595);
      textFlow.getChildren().addAll(text1, text2, text3, text4, text5);
      //设置舞台
      Group root = new Group(textFlow);
      Scene scene = new Scene(root, 595, 250, Color.BEIGE);
      stage.setTitle("Text Flow Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出


相关文章