View RSS Feed

Java AWT

Measuring Text

Rate this Entry
by , 03-07-2012 at 05:46 PM (1026 Views)
For measuring text properly you shall be learning certain important methods and also few mistakes shall be avoided. Font metrics are considered as the measure of the text which has been rendered by the font object like, height of line in font. By using FontMetrics instance, you can measure text easily and this is one of the most common way to do so. E.g,
Java Code:
// get metrics from the graphics
FontMetrics metrics = graphics.getFontMetrics(font);
// get the height of a line of text in this
// font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font
// and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the
// text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);
For many applications, such kind of way is sufficient to space the lines of text evenly or also to size the swing components.

Submit "Measuring Text" to Facebook Submit "Measuring Text" to Digg Submit "Measuring Text" to Submit "Measuring Text" to StumbleUpon Submit "Measuring Text" to Google