Java AWT Create Font Object

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.

Java AWT Create Font Object

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

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

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.

4 thoughts on “Java AWT Create Font Object

Leave a Reply

Your email address will not be published. Required fields are marked *