If I need an instance of Graphics2D to get the LineMetrics/FontMetrics of a font - how shall I create this instance?

Curtis Hatter

To obtain an instance of LineMetrics (it's the preferred method in 2D api) you call one of the Font's getLineMetrics() methods. There are 4 different getLineMetrics() methods, one thing they all have in common though is that they all require a FontRenderContext object.

To obtain the FontRenderContext you can either create one yourself:

public FontRenderContext(AffineTransform tx, boolean isAntialised, boolean usesFractionalMetrics)

Or you can call the Graphics2D's getFontRenderContext() method.

public abstract FontRenderContext getFontRenderContext()

The FontRenderContext is affected by RenderingHints so the returned object may be different each time.

Once you have the FontRenderContext you can then create the LineMetrics by providing the String, char[] array, or CharacterIterator, plus the FontRenderContext and possibly a couple more variables. The methods are:

public LineMetrics getLineMetrics(String str, FontRenderContext fcr)
public LineMetrics getLineMetrics(String str, int beginIndex, int limit, FontRenderContext fcr)
public LineMetrics getLineMetrics(char[] chars, int beginIndex, int limit, FontRenderContext fcr)
public LineMetrics getLineMetrics(CharacterIterator ci, int beginIndex, int limit, FontRenderContext)


Davanum Srinivas adds:

There are two options (only on Java2). The first option is to typecast the parameter to your paint method as follows:

public void paint(Graphics g) {
   Graphics2D g2 = (Graphics2D) g;
The second option is to create a buffered image and use createGraphics method as follows:

BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
Graphics2D big = bi.createGraphics();