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 :)
Java AWT Programming Project By default, JLabel can display a text in the horizontal position and we can rotate a JLabel text by implementing the rotate() method of Graphics2D class inside the paintComponent().
The simplest way to rotate an image in Java is to use the AffineTransformOp class. You can load an image into Java as a BufferedImage and then apply the rotate operation to generate a new BufferedImage. You can use Java's ImageIO or a third-party image library such as JDeli to load and save the image.
This method will rotate the text and will render all other shapes the same.
Graphics2D g2 = (Graphics2D) g; Font font = new Font(null, Font.PLAIN, 10); AffineTransform affineTransform = new AffineTransform(); affineTransform.rotate(Math.toRadians(45), 0, 0); Font rotatedFont = font.deriveFont(affineTransform); g2.setFont(rotatedFont); g2.drawString("A String",0,0); g2.dispose();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With