Sometimes you may want to know the precise information about the font such as height, ascent, decent and leading etc. For example, if you want to display string in the center of the panel.
This information is made available using the FontMetrics class. To use the FontMetrics class in Java, you need to understand the following terms that are used in FontMetrics class whichare the same as used by typesetters.
• Baseline: It refers to the line on which the bottom of the most characters occurs.
• Ascent: It is the distance from the baseline to the top of an ascender which is the upper part of a letter like b or k or an uppercase letter.
• Descent: It is the distance from the baseline to a descender which is the lower part of letters such as y or p.
• Leading: It is spacing between the descent of one line of text and the ascent of the next line of text.
• Height: It is the sum (in pixels) of the ascent, descent and leading values.
import java.awt.*;
class FontMetricsExample extends Frame
{
TextArea txtData;
String str="" ;
FontMetricsExample()
{
Font myfont = new Font("Serif",Font.BOLD,12);
FontMetrics metrics = getFontMetrics(myfont);
str=str+ "Ascent of the Font = " + metrics.getAscent();
str = str + "\n Maximum Ascent of the Font = " + metrics.getMaxAscent();
str = str + "\n Descent of the Font = " + metrics.getDescent();
str = str + "\n Maximum Desent of the Font = " + metrics.getMaxDescent();
str = str + "\n Leading of the Font = " + metrics.getLeading();
str = str + "\n Height of the Font = " + metrics.getHeight();
txtData=new TextArea(10,15);
txtData.setText(str);
add(txtData);
}
}
class FontMetricsJavaExample
{
public static void main(String [] args)
{
FontMetricsExample frame = new FontMetricsExample();
frame.setTitle("Font Metrics in Java Example");
frame.setSize(300,1500);
frame.setVisible(true);
}
}