jacknad
jacknad

Reputation: 13739

How to rotate Swing text?

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?

Upvotes: 8

Views: 5565

Answers (3)

StanislavL
StanislavL

Reputation: 57381

Not JLabel but JEditorPane content http://java-sl.com/vertical.html

Upvotes: 2

user949300
user949300

Reputation: 15729

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)

Upvotes: 10

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.

Upvotes: 2

Related Questions