JavaFX는 노드(node)의 위치를 지정하기 위한 로컬 좌표계 외에도, 텍스트 노드(Text Node)를 위해 별도의 추가 좌표계를 제공합니다. 이 좌표계를 이해하면 텍스트가 화면상에서 어떻게 배치되는지 더욱 정확하게 제어할 수 있습니다.
textOrigin 속성이란?
textOrigin 속성은 부모(parent) 좌표계 안에서 텍스트 노드의 좌표 원점(origin)이 어디에 놓일지를 결정합니다. 이 속성의 값은 setTextOrigin() 메서드를 통해 설정할 수 있으며, 해당 메서드는 VPos라는 열거형(enum)의 상수 중 하나를 인자로 받습니다.
VPos 열거형에는 다음과 같은 4가지 상수가 정의되어 있습니다.
- BASELINE — 텍스트의 베이스라인(기준선)을 원점으로 지정합니다. (기본값)
- BOTTOM — 텍스트 영역의 아래쪽 가장자리를 원점으로 지정합니다.
- CENTER — 텍스트 영역의 수직 중앙을 원점으로 지정합니다.
- TOP — 텍스트 영역의 위쪽 가장자리를 원점으로 지정합니다.
예제 코드
아래 예제는 텍스트 파일의 내용을 읽어 화면에 출력하면서, setTextOrigin() 메서드로 텍스트의 원점을 VPos.TOP으로 설정하는 방법을 보여줍니다.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Text;
public class TextOriginExample 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()+"
");
}
//Text 객체를 생성합니다.
Text text = new Text(10.0, 25.0, sb.toString());
//텍스트 줄바꿈 너비를 설정합니다.
text.setWrappingWidth(565);
//텍스트 원점을 TOP으로 설정합니다.
text.setTextOrigin(VPos.TOP);
//Stage를 구성하고 화면에 표시합니다.
Group root = new Group(text);
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Text Origin (TOP)");
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.
실행 결과
위 코드를 실행하면 텍스트 원점이 TOP(위쪽 가장자리) 기준으로 지정되어 다음과 같이 출력됩니다.

같은 방식으로 setTextOrigin() 메서드에 전달하는 값을 바꾸면, 텍스트의 세로 위치가 그에 맞게 달라진 결과를 확인할 수 있습니다.
BASELINE(베이스라인 기준) —

BOTTOM(아래쪽 기준) —

CENTER(중앙 기준) —

이처럼 textOrigin 속성을 활용하면 텍스트 노드가 부모 컨테이너 내에서 기준이 되는 지점을 자유롭게 조절할 수 있으며, 라벨 정렬이나 다른 노드와의 위치 관계를 정밀하게 맞추는 데 유용하게 사용됩니다.