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

JavaFX에서 텍스트 노드의 줄 간격을 조정하는 방법

JavaFX에서 javafx.scene.text.Text 클래스의 lineSpacing(줄 간격) 속성은 텍스트 노드 내에서 각 줄 사이의 세로 간격을 지정합니다.

이 속성의 값을 설정하려면 setLineSpacing() 메서드를 사용합니다. 이 메서드는 double 타입의 값을 매개변수로 받아들이며, 지정한 값만큼 텍스트 줄 사이에 세로 간격을 적용합니다.

예제

다음 예제는 텍스트 파일의 내용을 읽어와 Text 객체에 표시하고, setLineSpacing() 메서드를 사용해 줄 간격을 설정하는 코드입니다.

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 TextSpacing extends Application {
    public void start(Stage stage) throws FileNotFoundException {
       // 텍스트 파일의 내용을 읽어옵니다.
       InputStream inputStream = new FileInputStream("D:\\sample_text.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.JUSTIFY);
       // 줄 간격 설정
       text.setLineSpacing(2.0);
       // 스테이지 설정
       Group root = new Group(text);
       Scene scene = new Scene(root, 595, 150, Color.BEIGE);
       stage.setTitle("Line Spacing (2.0)");
       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.

실행 결과

위 코드를 실행하면 줄 간격이 2.0으로 설정된 상태로 텍스트가 화면에 출력됩니다.

JavaFX에서 텍스트 노드의 줄 간격을 조정하는 방법

같은 방식으로 setLineSpacing() 메서드의 매개변수 값을 8.0으로 변경하면, 다음과 같이 줄 간격이 더 넓어진 결과를 확인할 수 있습니다.

JavaFX에서 텍스트 노드의 줄 간격을 조정하는 방법

이처럼 setLineSpacing() 메서드를 활용하면 JavaFX 애플리케이션에서 텍스트의 가독성을 손쉽게 개선할 수 있습니다. 값이 커질수록 줄 사이의 간격이 넓어지고, 작아질수록 간격이 좁아집니다.