Java Retrieve Font Information

Java Retrieve Font Information

Summary: By the end of this tutorial "Java Retrieve Font Information", you will be comfortable to retrieve the components of Font object like font name, style and size.

The Font object (discussed earlier) comprises of three components – font name as string, font style and font size as integer values. We can retrieve these three components from a Font object.

Supporting Methods of java.awt.Font class
  • int getName(): Returns the font name (of the font object) as string.
  • int getStyle(): Returns the font style as an integer value.
  • int getSize(): Returns the font size as an integer value.
  • String getFamily(): Returns the font family, as string, for which the font belongs.
Supporting Method of java.awt.Graphics class
  • Font getFont(): Returns a Font object that represents current font or active font of Graphics object.

The following program uses the all the above five methods.

import java.awt.*;
public class GetFontInfo extends Frame 
  String str;  	
  Font f1;
  public GetFontInfo()  
    f1 = new Font("SansSerif", Font.ITALIC, 18);
    setTitle("Getting Font Particulars");
    setSize(550, 240);
  public void paint(Graphics g)  
    String fn1, fn2;   
    int fstyle, fsize;

    fn1 = f1.getName(); 
    fstyle = f1.getStyle();
    fsize = f1.getSize();
    if(fstyle == Font.PLAIN) 	
      fn2 = "Plain";
    else if(fstyle == Font.BOLD) 	
      fn2 = "Bold";
    else if(fstyle == Font.ITALIC) 	
      fn2 = "Italic";
      fn2 = "Bold and Italic";

    g.drawString("The Font components of f1 object are:", 50, 60);
    g.drawString("Font Name:   " + fn1, 70, 90) ;
    g.drawString("Font Style:  " + fn2, 70, 110) ;
    g.drawString("Font Size:   " + fsize, 70, 130) ;
    g.drawString("Font Family: " + f1.getFamily(), 70, 150) ;
	  			         // retrieve the active (default) font info
    g.drawString("Default Font: " + g.getFont(), 70, 180);
    g.setFont(f1);                 // now active is f1                              
    g.drawString("Active Font: " + g.getFont(), 70, 220);
  public static void main(String args[ ])   
    new GetFontInfo();

Java Retrieve Font Information
Output screen of of Java Retrieve Font Information

The methods f1.getName(), f1.getStyle(), f1.getSize() and f1.getFamily() return the font name, style, size and family of the Font object f1.


getFont() is a method of Graphics class and returns the active font particulars as an object of Font. If no font is set with setFont() method, the default font is returned. Observe the screenshot for the default font particulars.

Leave a Comment

Your email address will not be published.