Java Swing Tutorial - Java Swing Font








An object of the java.awt.Font class represents a font in a Java program.

To create an object of the Font class, use its constructor.

To install a font to a component, use the setFont(Font f) method of the component.

Java defines five logical font family names and maps them to physical font family names for different system.

The five logical font family names are as follows:

  • Serif
  • SansSerif
  • Dialog
  • DialogInput
  • Monospace

The following code creates Font objects:

To create serif, plain font of size 10

Font  f1  = new Font(Font.SERIF, Font.PLAIN,  10);

To create SansSerif, bold font of size 10

Font  f2  = new Font(Font.SANS_SERIF,  Font.BOLD, 10);

To create dialog, bold font of size 15

Font  f3  = new Font(Font.DIALOG,  Font.BOLD, 15);

To create dialog input, bold and italic font of size 15

Font  f4  = new Font(Font.DIALOG_INPUT,  Font.BOLD|Font.ITALIC, 15);

To set the font for a Swing component, use its setFont() method of the component.

JButton closeButton  = new JButton("Close");
closeButton.setFont(f4);

Use the getFamily(), getStyle(), and getSize() methods to get the family name, style and size of a font object, respectively.