Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

JavaFX에서 텍스트 정렬을 조정하는 방법


wrappingWidth 속성으로 텍스트 폭 지정하기

JavaFX에서 wrappingWidth 속성에 값을 설정하면 사용자 좌표계(user space) 기준으로 텍스트에 고정된 폭을 지정할 수 있습니다. 값을 지정하면 해당 폭이 텍스트 영역(bounding box)의 경계로 간주되며, 텍스트는 주어진 폭 안에 맞춰 배치됩니다.

만약 이 속성에 별도의 값을 지정하지 않으면, 기본적으로 텍스트에서 가장 긴 줄의 길이가 경계 상자의 너비로 사용됩니다.

setTextAlignment() 메서드로 정렬 조정하기

텍스트 정렬(text alignment)이란 경계 상자 내부에서 텍스트를 수평 방향으로 어떻게 배치할지 결정하는 것을 말합니다. JavaFX에서는 setTextAlignment() 메서드를 사용하여 텍스트 정렬을 간단히 조정할 수 있습니다. 이 메서드는 TextAlignment 열거형(enum)의 상수 중 하나를 인자로 받으며, 전달된 값에 따라 텍스트가 정렬됩니다. TextAlignment 열거형은 다음과 같은 4가지 상수를 제공합니다.

  • CENTER − 텍스트를 경계 상자의 가운데에 정렬합니다.

  • JUSTIFY − 경계 상자 안에서 텍스트를 양쪽 끝에 맞춰 균등하게 정렬합니다.

  • 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 객체 생성
        Text text = new Text(10.0, 25.0, sb.toString());
        // 텍스트 줄바꿈 폭 설정
        text.setWrappingWidth(565);
        // 텍스트 정렬 방식 설정
        text.setTextAlignment(TextAlignment.Right);
        // 스테이지 설정
        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에서 텍스트 정렬을 조정하는 방법

같은 방식으로 정렬 값을 변경하면 아래와 같은 결과를 확인할 수 있습니다.

LEFT(왼쪽 정렬) −

JavaFX에서 텍스트 정렬을 조정하는 방법

CENTER(가운데 정렬) −

JavaFX에서 텍스트 정렬을 조정하는 방법

JUSTIFY(양쪽 정렬) −

JavaFX에서 텍스트 정렬을 조정하는 방법