Is there a way to rotate Swing text such as in a JLabel between 0 and 360 (or between -180 and 180) degrees in 1 degree steps?
Asked
Active
Viewed 5,435 times
3 Answers
10
Yes. Look at Graphics2D.rotate(). For a JLabel, I think you could override the paintComponent() method to call rotate(x), then call the existing paintComponent(), then call rotate(-x). e.g.
protected void paintComponent(Graphics g) {
Graphics2D g2 = ( Graphics2D )g;
g2.rotate(theta);
super.paintComponent(g2);
g2.rotate(-theta);
}
I haven't tried this. You might need to add an offset, see Graphics2D.rotate(double theta, double x, double y)

user949300
- 15,364
- 7
- 35
- 66
-
+1. Just tried it and it works. But it rotates around the origin, so a translate is needed too - assuming the poster wants to rotate around the center of the text. – S.L. Barth is on codidact.com Dec 19 '11 at 15:26
2
I do not believe that Swing offers explicit support for this.
However, you can turn your text into an image, and rotate that, using the AffineTransform class.
Here is some example code, apparently taken from the book "Swing Hacks", for writing text backwards. You can easily modify it for rotating text, although you will have to add some code for the animation effect.

S.L. Barth is on codidact.com
- 8,198
- 71
- 51
- 66