Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีปรับการจัดตำแหน่งข้อความใน JavaFX

คุณสามารถตั้งค่าความกว้างคงที่สำหรับข้อความใน user space โดยตั้งค่าให้คุณสมบัติ wrappingWidth เมื่อทำแล้ว ความกว้างที่กำหนดจะถูกพิจารณาเป็นขอบเขตของข้อความใน user coordinates และข้อความจะจัดเรียงภายในความกว้างที่กำหนด

หากไม่ได้ตั้งค่าคุณสมบัตินี้ ค่าเริ่มต้นจะใช้ความยาวบรรทัดที่ยาวที่สุดในข้อความเป็นความกว้างของ bounding box

Text alignment คือการจัดเรียงข้อความแนวนอนภายใน bounding box สามารถปรับ alignment ได้ด้วยเมธอด setTextAlignment() เมธอดนี้รับค่าคงที่ของ enum TextAlignment และจัดข้อความตามนั้น Enum นี้มี 4 ค่าคือ:

  • CENTER - จัดข้อความกึ่งกลางของ bounding box
  • JUSTIFY - จัดข้อความให้เต็มความกว้าง (justify) ภายใน bounding box
  • LEFT - จัดข้อความชิดซ้าย
  • RIGHT - จัดข้อความชิดขวา

ตัวอย่าง

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 {
        // อ่านเนื้อหาไฟล์
        InputStream inputStream = new FileInputStream("D:\\sample.txt");
        Scanner sc = new Scanner(inputStream);
        StringBuffer sb = new StringBuffer();
        while(sc.hasNext()) {
            sb.append(" " + sc.nextLine() + "\n");
        }
        // สร้าง Text object
        Text text = new Text(10.0, 25.0, sb.toString());
        // Wrapping
        text.setWrappingWidth(565);
        // ตั้งค่า alignment
        text.setTextAlignment(TextAlignment.RIGHT);
        // ตั้งค่า 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

สมมติเนื้อหา sample.txt ดังนี้:

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.

ผลลัพธ์

วิธีปรับการจัดตำแหน่งข้อความใน JavaFX

หากเปลี่ยนค่า alignment จะได้ผลลัพธ์ดังนี้:

LEFT -

วิธีปรับการจัดตำแหน่งข้อความใน JavaFX

CENTER -

วิธีปรับการจัดตำแหน่งข้อความใน JavaFX

JUSTIFY -

วิธีปรับการจัดตำแหน่งข้อความใน JavaFX