Bạn có thể đặt chiều rộng cố định cho văn bản trong không gian người dùng bằng cách đặt giá trị cho thuộc tính wrappingWidth. Khi làm vậy, chiều rộng đã cho được coi là ranh giới của văn bản trong tọa độ người dùng và văn bản được sắp xếp trong chiều rộng đó.
Nếu bạn không đặt giá trị cho thuộc tính này, theo mặc định, độ dài của dòng dài nhất trong văn bản được coi là chiều rộng của hộp giới hạn.
Căn chỉnh văn bản là sự sắp xếp văn bản theo chiều ngang trong hộp giới hạn. Bạn có thể điều chỉnh căn chỉnh văn bản bằng phương thức setTextAlignment(). Phương thức này chấp nhận một trong các hằng số của enum TextAlignment và điều chỉnh văn bản tương ứng. Enum này cung cấp 4 hằng số:
- CENTER - Căn giữa văn bản trong hộp giới hạn.
- JUSTIFY - Canh đều căn chỉnh văn bản trong hộp giới hạn.
- LEFT - Căn trái văn bản.
- RIGHT - Căn phải văn bản.
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;
import javafx.scene.text.TextAlignment;
public class TextAllignment 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");
}
// Tạo đối tượng Text
Text text = new Text(10.0, 25.0, sb.toString());
// Bọc văn bản
text.setWrappingWidth(565);
// Thiết lập căn chỉnh
text.setTextAlignment(TextAlignment.RIGHT);
// Thiết lập Stage
Group root = new Group(text);
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Text Alignment");
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:
Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more.
Kết quả

Tương tự, nếu thay đổi giá trị căn chỉnh, bạn sẽ nhận được kết quả tương ứng:
LEFT -

CENTER -

JUSTIFY -
