如何在 JavaFX 中创建文本流布局?
为了在应用程序中创建丰富的文本内容,JavaFX 提供称为文本流的特殊布局,该布局由**javafx.scene.layout.TextFlow**类表示。使用此布局,您可以在一个文本流中布局多个文本节点。
由于它们是独立的节点,因此您可以为它们设置不同的字体。如果您尝试向此布局添加非文本节点,则它们将被视为嵌入对象,并且只是简单地插入到文本之间。
此类具有两个属性 −
lineSpacing − 该属性(double)用于指定文本对象之间的间距。您可以使用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 {
//Creating a text object
Text text1 = new Text(30.0, 110.0, "Hi ");
//Setting the font
Font font1 = Font.font("Brush Script MT", FontWeight.BOLD, 75);
text1.setFont(font1);
//Setting the color of the text
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);
//Setting the color of the text
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);
//Setting the color of the text
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");
//Setting font to the text
text5.setFont(new Font("Ink Free",30));
text5.setFill(Color.MEDIUMVIOLETRED);
//Creating the text flow
TextFlow textFlow = new TextFlow();
textFlow.setPrefWidth(595);
textFlow.getChildren().addAll(text1, text2, text3, text4, text5);
//Setting the stage
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);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP