Java Graphics How to - Draw angle text








Question

We would like to know how to draw angle text.

Answer

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
//from   w w  w.  j a v  a 2s . c  o m
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new TestPane());
    frame.pack();
    frame.setVisible(true);
  }
}
class TestPane extends JPanel {
  @Override
  public Dimension getPreferredSize() {
    return new Dimension(200, 200);
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    String text = "I don't see the problem";
    FontMetrics fm = g2d.getFontMetrics();
    int x = (getWidth() - fm.stringWidth(text)) / 2;
    int y = ((getHeight() - fm.getHeight()) / 2) + fm.getDescent();
    g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(45),
        getWidth() / 2, getHeight() / 2));
    g2d.drawString(text, x, y);
    g2d.dispose();
  }
}