如何在 JavaFX 中将文本换行到窗口宽度内?

javaobject oriented programmingprogramming更新于 2025/10/12 9:16:17

在 JavaFX 中,文本节点由 Javafx.scene.text.Text  类表示。要在 JavaFx 窗口中插入/显示文本,您需要 −

  • 实例化 Text 类。

  • 使用 setter 方法或将它们作为参数传递给构造函数,设置位置和文本字符串等基本属性。

  • 将创建的节点添加到 Group 对象。

如果您传递的文本中的行长超过窗口的宽度,则文本的一部分将被截断,如下所示 −

作为一种解决方案,您可以通过将值设置为属性来将文本换行到窗口的宽度内使用 setWrappingWidth() 方法进行换行。

此方法接受一个双精度值,表示文本的宽度(以像素为单位)。如果传递的值小于窗口的宽度,则文本将换行在其中(给定的宽度)。

示例

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.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class WrappingTheText extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //读取文本文件的内容。
      InputStream inputStream = new FileInputStream("D:\sample.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(590);
      //设置舞台
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Wrapping The Text");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

sample.txt

假设以下是sample.txt文件的内容 −

JavaFX is a Java library used to build Rich Internet Applications. The applications written 
using this library can run consistently across multiple platforms. The applications developed 
using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc..
To develop GUI Applications using Java programming language, the programmers rely on libraries 
such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers 
can now develop GUI applications effectively with rich content.

输出

Font Name: Brush Script MT

输出


相关文章


有用资源