如何在文本流布局中设置文本的对齐方式?
javafxobject oriented programmingprogramming更新于 2025/6/26 2:22:17
为了在我们的应用程序中创建富文本内容,JavaFX 提供了一种称为文本流的特殊布局,由 javafx.scene.layout.TextFlow 类表示。使用此功能,您可以在单个文本流中布局多个文本节点。
由于它们是独立的节点,因此您可以为它们设置不同的字体。如果您尝试向此布局添加文本以外的节点,它们将被视为嵌入对象,并直接插入文本之间。
设置文本对齐方式 −
TextFlow 类的 textAlignment 属性指定布局中文本的水平对齐方式。您可以使用 setTextAlignment() 方法设置此属性的值。此方法接受四个值 −
TextAlignment.RIGHT
TextAlignment.LEFT
TextAlignment.CENTER
TextAlignment.JUSTIFY
要设置文本流所需的对齐方式,请通过传递适当的值来调用此方法。
示例
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 { //创建文本对象 Text text1 = new Text("Welcome To Tutorialspoint"); Font font1 = Font.font("Brush Script MT", FontWeight.BOLD, 50); text1.setFont(font1); //设置文本颜色 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"); //设置文本字体 Font font2 = Font.font("Ink Free", FontWeight.BOLD, 35); text3.setFont(font2); text3.setFill(Color.DIMGRAY); //创建文本流 TextFlow textFlow = new TextFlow(); //包裹文本流的内容 textFlow.setPrefWidth(595); textFlow.getChildren().addAll(text1, text2, text3); //设置文本流的内边距 textFlow.setPadding(new Insets(15, 15, 15, 15)); //设置舞台 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); } }