Monday, November 28, 2011

Aligning text in java.awt.Graphics2D

Aligning text in java.awt.Graphics2D

@Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
{
Graphics2D g2 = (Graphics2D) g;
double pageWidth = pageFormat.getImageableWidth();

FontMetrics fm = g2.getFontMetrics(g2.getFont());
String title = "This is my title";
int titleWidth = fm.stringWidth(title);

g2.drawString(title, (int)pageWidth - titleWidth, 20);
}

Graphics2D class is often used to print pages in java. You can easily align text to left/right by using this method.