如何在 JavaFX 中调整文本对齐方式?
您可以通过设置 wrappingWidth 属性的值来设置用户空间中文本的固定宽度。这样做之后,给定的宽度将被视为用户坐标中文本的边界,并且文本将在此给定宽度内排列。
如果您没有为该属性提供任何值,则默认情况下,文本中最长行的长度将被视为边界框的宽度。
文本对齐是指文本在边界框内的水平排列方式。您可以使用 setTextAlignment() 方法调整文本的对齐方式。此方法接受名为 *TextAlignment* 的枚举的常量之一,并相应地调整文本。此枚举提供 3 个常量:
CENTER - 将文本与边界框的中心对齐。
JUSTIFY - 在边界框内对齐文本。
LEFT - 将文本左对齐。
RIGHT - 将文本右对齐。
示例
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
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.Text;
import javafx.scene.text.TextAlignment;
public class TextAllignment extends Application {
public void start(Stage stage) throws FileNotFoundException {
//Reading the contents of a text file.
InputStream inputStream = new FileInputStream("D:\sample.txt");
Scanner sc = new Scanner(inputStream);
StringBuffer sb = new StringBuffer();
while(sc.hasNext()) {
sb.append(" "+sc.nextLine()+"\n");
}
//Creating a text object
Text text = new Text(10.0, 25.0, sb.toString());
//Wrapping the text
text.setWrappingWidth(565);
//Setting the alignment
text.setTextAlignment(TextAlignment.Right);
//Setting the stage
Group root = new Group(text);
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Text Alignment");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}sample.txt
假设以下是 sample.txt 文件的内容:
Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more.
输出

同样,如果您更改对齐值,您将相应地获得输出:
左对齐 -

居中对齐 -

两端对齐 -

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP