Java AWT Create Font Object


Important text can be made eye-catching by displaying in attractive fonts. A font represents a combination of a font name (like Monospaced), font style (like bold) and font size (like 20).

Following is the class signature

public class Font extends Object implements Serializable

The Font constructor takes three parameters to create a Font object.

Font f1 = new Font(String fontName, int fontStyle, int fontSize);

To give the font style as an integer value, the Font class comes with 3 symbolic constants.

public final static int PLAIN = 0;
public final static int BOLD = 1;
public final static int ITALIC = 2;

There are five font style attributes supported by JVM are

1. Monospaced
2. Serif
3. SansSerif
4. Dialog
5. DialogInput

If anyone other than the above five mentioned in font object creation, it is not an error, but gives the default Dialog, plain and size 12.

Java AWT Create Font Object – 4 styles

Font f1 = new Font("Monospaced", Font.BOLD, 15);
Font f2 = new Font("Serif", Font.ITALIC, 20);
Font f3 = new Font("SansSerif", Font.PLAIN, 19);
Font f4 = new Font("DialogInput", Font.BOLD + Font.ITALIC, 25);

The following example shows how to create Font object and apply to the string.

import java.awt.*;
public class UsingFonts extends Frame
{  
  public void paint(Graphics g)
  {
    Font f1 = new Font("Monospaced", Font.BOLD, 12);
    g.setFont(f1);

    g.drawString("Font Particulars: " + g.getFont(), 15, 60);
    g.drawString("Font Name: " + f1.getFontName(), 15, 80);
    g.drawString("Font Style: " + f1.getStyle(), 15, 100);
    g.drawString("Font Size: " + f1.getSize(), 15, 120);
    g.drawString("isBold(): " + f1.isBold(), 15, 140);
    g.drawString("isItalic(): " + f1.isItalic(), 15, 160);
    g.drawString("isPlain(): " + f1.isItalic(), 15, 180);
  }
  public static void main(String args[])
  {
    Frame myFrame = new UsingFonts();
    myFrame.setSize(600, 250);
    myFrame.setVisible(true);
  }
}

Java AWT Create Font Object

Font f1 = new Font("Monospaced", Font.BOLD, 12);
g.setFont(f1);

A Font object f1 is created with font name of Monospaced, style bold and size 12. setFont() method of Graphics class sets the font to the text. For a similar program with many font and color objects refer ColorsAndFonts.java.

Note: Observe another style of creating frame. Frame is created in the main() method instead of conventional constructor as done in other programs.

The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code close icon to work.

5 thoughts on “Java AWT Create Font Object”

  1. sir,swing is platform independent so we should use it instead of awt.Then what’s the point of learning awt when we are having swing?

Leave a Comment

Your email address will not be published.