Rotated Text in Java Swing 2D
I was, um….Googling myself….and found an old post I made to comp.lang.java.programmer in 1999, answering someone’s question about how to draw rotated text in Swing.
I looked around, and ten years later, there still doesn’t seem to be much easily-found information on this. So, here it is again….
I just worked this one out, and thought I'd respond, since the faq wasn't very helpful in my situation, and probably isn't for the situation that David described. Correct me if I'm wrong, but: The method described in the faq works great if you want to apply a transform to the entire graphics context. If all you want is some rotated text on top of something that you've already drawn, this doesn't seem to be the way to do it. What I did instead was to derive a font with the desired transform, and then use that font in a drawText call, thusly:
:::java
private void label_line(Graphics g, double x, double y, double theta, String label) {
Graphics2D g2D = (Graphics2D)g;
// Create a rotation transformation for the font.
AffineTransform fontAT = new AffineTransform();
// get the current font
Font theFont = g2D.getFont();
// Derive a new font using a rotatation transform
fontAT.rotate(theta);
Font theDerivedFont = theFont.deriveFont(fontAT);
// set the derived font in the Graphics2D context
g2D.setFont(theDerivedFont);
// Render a string using the derived font
g2D.drawString(label, (int)x, (int)y);
// put the original font back
g2D.setFont(theFont);
}
theta (the rotation angle) is in radians. For vertical text, use 90 * java.lang.Math.PI/180 or 270 * java.lang.Math.PI/180 depending on whether you want the text top-top-bottom or bottom-to-top I hope that this will save you hours of aggravation.
Thanks to Google Groups for saving all of this old stuff!