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

วิธี wrap ข้อความให้อยู่ในความกว้างหน้าต่างใน JavaFX

ใน JavaFX โหนดข้อความแทนด้วยคลาส Javafx.scene.text.Text เพื่อแทรก/แสดงข้อความในหน้าต่าง JavaFX ต้อง:

  • สร้างอินสแตนซ์คลาส Text
  • ตั้งค่าคุณสมบัติพื้นฐาน เช่น ตำแหน่งและสตริงข้อความ ใช้ setter methods หรือส่งเป็นอาร์กิวเมนต์ให้คอนสตรัคเตอร์
  • เพิ่มโหนดที่สร้างเข้าไปใน Group object

หากความยาวบรรทัดในข้อความที่ส่งเข้ามายาวกว่าความกว้างของหน้าต่าง ส่วนของข้อความจะถูกตัดทิ้ง

วิธีแก้: wrap ข้อความภายในความกว้างของหน้าต่างโดยตั้งค่าคุณสมบัติ wrapping width ด้วยเมธอด setWrappingWidth()

เมธอดนี้รับค่า double แทนความกว้าง (พิกเซล) ของข้อความ หากส่งค่าน้อยกว่าความกว้างหน้าต่าง ข้อความจะ wrap อยู่ภายในความกว้างนั้น

ตัวอย่าง

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.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;

public class WrappingTheText 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(590);
        // ตั้งค่า Stage
        Group root = new Group(text);
        Scene scene = new Scene(root, 595, 300, Color.BEIGE);
        stage.setTitle("Wrapping The 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.

ผลลัพธ์

Font Name: Brush Script MT

ผลลัพธ์

วิธี wrap ข้อความให้อยู่ในความกว้างหน้าต่างใน JavaFX