如何在 JavaFX 中创建文本节点?

javaobject oriented programmingprogramming更新于 2025/10/12 7:40:17

在 JavaFX 中,文本节点由 javafx.scene.text.Text 类表示。您可以通过实例化此类将文本添加到 JavaFX 窗口。

以下是文本节点 − 的基本属性

  • X − 此属性表示文本的 x 坐标。您可以使用 setX() 方法为此属性设置值。

  • Y − 此属性表示文本的 y 坐标。您可以使用 setY() 方法为此属性设置值。

  • text − 此属性表示要在 JavaFX 窗口上显示的文本。您可以使用 setText() 方法设置此属性的值。

要在 JavaFx 窗口中插入/显示文本,您需要 −

  • 实例化 Text 类。

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

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

示例

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;
导入 javafx.scene.paint.Color;
导入 javafx.stage.Stage;
导入 javafx.scene.text.Text;
public class CreatingText 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");
      }
      String str = sb.toString();
      //创建文本对象
      Text text = new Text();
      //设置文本的属性
      text.setText(str);
      text.setWrappingWidth(580);
      text.setX(10.0);
      text.setY(25.0);
      //设置Stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Displaying 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.

输出


相关文章


有用资源