JLabel เป็นคลาสย่อยของ JComponent แสดงข้อความ/รูปภาพบน GUI แสดง ข้อความอ่านอย่างเดียวบรรทัดเดียว, รูปภาพ, หรือ ทั้งสองอย่าง สร้าง PropertyChangeListener ได้ ค่าเริ่มต้นแสดงข้อความแนวนอน หมุนได้ด้วยเมธอด rotate() ของ Graphics2D ภายใน paintComponent()
ไวยากรณ์
public abstract void rotate(double theta, double x, double y)
ตัวอย่าง: หมุนข้อความ JLabel
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 g2d = (Graphics2D) g;
// หมุน 0.6 เรเดียน รอบจุดกึ่งกลาง
g2d.rotate(0.6, getX() + getWidth() / 2.0, getY() + getHeight() / 2.0);
super.paintComponent(g);
}
}
public static void main(String[] args) {
new RotateJLabelTest();
}
}
ผลลัพธ์

คำอธิบาย: rotate(theta, x, y) หมุนรอบจุด (x,y) theta เป็นเรเดียน (0.6 ≈ 34°) คำนวณขนาดข้อความด้วย FontMetrics เพื่อ setBounds ให้ถูกต้อง