How to rotate text with Graphics2D in Java?

Rafael Carrillo picture Rafael Carrillo · Apr 10, 2012 · Viewed 32.3k times · Source

I want to rotate text on a JPanel using Graphics2D..

My code is this:

double paso=d.width/numeroBarras;
        double alto=datos[i].valor;
        Font fBarras=new Font("Serif", Font.PLAIN, 15);
        g2.setFont(fBarras);
        Rectangle2D barra=new Rectangle2D.Double(x,d.height-alto,paso,alto);
        //g2.fill(barra);
        x+=paso;
        g2.draw(barra);
        g2.rotate(-Math.PI/2);
        g2.setColor(Color.BLACK);
        g2.drawString(datos[i].titulo,(float)alto,(float)paso)

This method must draw a rectangle and a text over the rectangle, but when i run this method all the graphic is rotated and i just want rotate the text ..

Thanks :)

Answer

Mersenne picture Mersenne · Apr 10, 2012

The method Graphics2D.rotate applies transform to all subsequent rendering operations. You can preserve a copy of transform (with getTransform()) before applying rotation, and then restore the original.

g2.draw(barra);
AffineTransform orig = g2.getTransform();
g2.rotate(-Math.PI/2);
g2.setColor(Color.BLACK);
g2.drawString(datos[i].titulo,(float)alto,(float)paso);
g2.setTransform(orig);