如何在 JavaFX 中建立文字節點?


在 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;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Text;
public class CreatingText 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");
      }
      String str = sb.toString();
      //Creating a text object
      Text text = new Text();
      //Setting the properties of text
      text.setText(str);
      text.setWrappingWidth(580);
      text.setX(10.0);
      text.setY(25.0);
      //Setting the 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.

輸出

更新於: 14-04-2020

656 次瀏覽

開啟你的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.