如何在JavaFX中调整文本节点中的行距?
javaobject oriented programmingprogramming更新于 2025/10/12 10:20:17
javafx.scene.text.text类的行距属性指定文本(节点)行之间的垂直行距。
您可以使用setLineSpacing()方法将值设置为此属性。此方法接受布尔值作为参数,并设置行之间的指定间距(垂直)。
示例
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 TextSpacing extends Application {
public void start(Stage stage) throws FileNotFoundException {
//读取文本文件的内容。
InputStream inputStream = new FileInputStream("D:\sample_text.txt");
Scanner sc = new Scanner(inputStream);
StringBuffer sb = new StringBuffer();
while(sc.hasNext()) {
sb.append(" "+sc.nextLine()+"\n");
}
//创建文本对象
Text text = new Text(10.0, 25.0, sb.toString());
//换行
text.setWrappingWidth(565);
//设置对齐方式
text.setTextAlignment(TextAlignment.JUSTIFY);
//设置空间
text.setLineSpacing(2.0);
//设置舞台
Group root = new Group(text);
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Line Spacing (2.0)");
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.
输出
同样,如果将行距设置为 8.0 − ,则输出结果如下

相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

