如何在 JavaFX 中 Text Flow 佈局中換行文字?


為了在我們的應用程式中建立富文字內容,JavaFX 提供了一種名為文字流的特殊佈局,由 javafx.scene.layout.TextFlow 類表示。透過使用它,你可以在單個文字流中佈局多個文字節點。

由於它們是獨立的節點,因此你可以為它們設定不同的字型。如果你嘗試向此佈局中新增非文字節點,它們將被視為嵌入物件,並只是插入到文字中。

換行文字

與 Label 和文字節點不同,文字流沒有提供任何換行文字的方法。但它確實有一個名為 prefWidth 的屬性,用於指定文字流佈局的期望寬度。你可以使用 setPrefWidth() 方法為此屬性設定值。

簡而言之,你可以使用 setPrefWidth()setPrefHeight() 方法以期望的寬度或高度換行文字。

示例

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.geometry.Insets;
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 TextFlow_Wrap extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a text object
      Text text1 = new Text("Welcome To Tutorialspoint");
      Font font1 = Font.font("Brush Script MT", FontWeight.BOLD, 50);
      text1.setFont(font1);
      //Setting the color of the text
      text1.setFill(Color.BLUEVIOLET);
      text1.setStrokeWidth(1);
      text1.setStroke(Color.CORAL);
      Text text2 = new Text(" We provide free tutorials for readers in various technologies ");
      text2.setFont(new Font("Algerian", 30));
      text2.setFill(Color.ORANGERED);
      Text text3 = new Text("We believe in easy learning");
      //Setting font to the text
      Font font2 = Font.font("Ink Free", FontWeight.BOLD, 35);
      text3.setFont(font2);
      text3.setFill(Color.DIMGRAY);
      //Creating the text flow
      TextFlow textFlow = new TextFlow();
      //Wrapping the content of the text flow
      textFlow.setPrefWidth(595);
      textFlow.getChildren().addAll(text1, text2, text3);
      //Setting padding to the text flow
      textFlow.setPadding(new Insets(15, 15, 15, 15));
      //Setting the stage
      Group root = new Group(textFlow);
      Scene scene = new Scene(root, 595, 250, Color.BEIGE);
      stage.setTitle("Text Flow");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於: 19-5-2020

787 次檢視

開啟您的 職業道路

透過完成課程獲得認證

開始
廣告
© . All rights reserved.