ใน JavaFX โหนดข้อความแทนด้วยคลาส javafx.scene.text.Text คุณสามารถเพิ่มข้อความในหน้าต่าง JavaFX ได้โดยการสร้างอินสแตนซ์ของคลาสนี้
คุณสมบัติพื้นฐานของ text node:
- X - พิกัด x ของข้อความ ตั้งค่าด้วย setX()
- Y - พิกัด y ของข้อความ ตั้งค่าด้วย setY()
- text - ข้อความที่จะแสดง ตั้งค่าด้วย setText()
ขั้นตอนการแทรก/แสดงข้อความใน JavaFX:
- สร้างอินสแตนซ์ Text class
- ตั้งค่าคุณสมบัติพื้นฐาน เช่น ตำแหน่งและข้อความ ใช้ setter หรือส่งให้คอนสตรัคเตอร์
- เพิ่มโหนดที่สร้างเข้าไปใน Group object
ตัวอย่าง
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 {
// อ่านเนื้อหาไฟล์
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 object
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.
ผลลัพธ์
