JLabel은 JComponent 클래스의 하위 클래스로, GUI 화면에 텍스트 안내문이나 정보를 표시하는 역할을 합니다. JLabel은 한 줄의 읽기 전용 텍스트, 이미지, 또는 텍스트와 이미지를 함께 표시할 수 있으며, PropertyChangeListener 인터페이스를 명시적으로 등록해 변경 사항을 감지할 수도 있습니다.
기본적으로 JLabel의 텍스트는 가로 방향으로 출력됩니다. 하지만 paintComponent() 메서드를 재정의하고 그 안에서 Graphics2D 클래스가 제공하는 rotate() 메서드를 호출하면, JLabel의 텍스트를 원하는 각도로 자유롭게 회전시킬 수 있습니다.
rotate() 메서드 문법
public abstract void rotate(double theta, double x, double y)
- theta : 회전 각도(라디안 단위)
- x, y : 회전의 중심점이 되는 좌표
예제 코드
아래 예제는 JLabel을 상속받은 사용자 정의 클래스를 만들고, paintComponent() 메서드에서 그래픽 객체를 회전시켜 기울어진 텍스트를 화면에 출력합니다.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class RotateJLabelTest extends JFrame {
public RotateJLabelTest() {
setTitle("Rotate JLabel");
JLabel label = new RotateLabel("TutorialsPoint");
add(label, BorderLayout.CENTER);
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private class RotateLabel extends JLabel {
public RotateLabel(String text) {
super(text);
Font font = new Font("Verdana", Font.ITALIC, 10);
FontMetrics metrics = new FontMetrics(font){};
Rectangle2D bounds = metrics.getStringBounds(text, null);
setBounds(0, 0, (int) bounds.getWidth(), (int) bounds.getHeight());
}
@Override
public void paintComponent(Graphics g) {
Graphics2D gx = (Graphics2D) g;
gx.rotate(0.6, getX() + getWidth()/2, getY() + getHeight()/2);
super.paintComponent(g);
}
}
public static void main(String[] args) {
new RotateJLabelTest();
}
}코드 핵심 포인트
- RotateLabel 클래스 : JLabel을 상속하여 생성자에서 폰트 크기에 맞게 컴포넌트 크기를 설정합니다.
- paintComponent() 재정의 : Graphics 객체를 Graphics2D로 형변환한 뒤 rotate(0.6, ...)를 호출해 컴포넌트 중심을 기준으로 약 34도 회전시킵니다.
- super.paintComponent(g) : 회전된 그래픽 상태에서 부모 클래스의 그리기 로직을 실행해 텍스트가 기울여져 렌더링됩니다.
실행 결과
프로그램을 실행하면 프레임 중앙에 "TutorialsPoint" 텍스트가 아래 그림처럼 기울어진 형태로 표시되는 것을 확인할 수 있습니다.

이처럼 Graphics2D의 rotate() 메서드를 활용하면 별도의 외부 라이브러리 없이도 Swing 컴포넌트의 텍스트나 이미지를 손쉽게 회전시킬 수 있습니다. 각도 값을 조절하면 세로 방향 텍스트, 대각선 워터마크 등 다양한 UI 효과도 구현할 수 있습니다.