You are here:   HomeJava ProgrammingAWT and AppletsFont Metrics in Java Example
by Dinesh Thakur Category: AWT and Applets

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);
       }
 }

Font Metrics in Java Example





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article