Trong JavaFX, nút văn bản được biểu diễn bởi lớp javafx.scene.text.Text. Bạn có thể thêm văn bản vào cửa sổ JavaFX bằng cách khởi tạo lớp này.
Dưới đây là các thuộc tính cơ bản của nút văn bản:
- X - Thuộc tính này đại diện cho tọa độ x của văn bản. Bạn có thể đặt giá trị bằng phương thức setX().
- Y - Thuộc tính này đại diện cho tọa độ y của văn bản. Bạn có thể đặt giá trị bằng phương thức setY().
- text - Thuộc tính này đại diện cho văn bản sẽ hiển thị trên cửa sổ JavaFX. Bạn có thể đặt giá trị bằng phương thức setText().
Để chèn/hiển thị văn bản trong cửa sổ JavaFX, bạn cần:
- Khởi tạo lớp Text.
- Thiết lập các thuộc tính cơ bản như vị trí và chuỗi văn bản, sử dụng các phương thức setter hoặc truyền chúng làm đối số cho constructor.
- Thêm nút đã tạo vào đối tượng Group.
Ví dụ
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 {
// Đọc nội dung file văn bản
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();
// Tạo đối tượng Text
Text text = new Text();
// Thiết lập thuộc tính văn bản
text.setText(str);
text.setWrappingWidth(580);
text.setX(10.0);
text.setY(25.0);
// Thiết lập 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
Giả sử nội dung file sample.txt như sau:
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.
Kết quả
