Using Special Fonts for Text Core Java

The “Not a Hello, World” program at the beginning of this chapter displayed a string in the default font. Often, you want to show text in a different font. You specify a font by its font face name. A font face name is composed of a font family name, such as “Helvetica,” and an optional suffix such as “Bold.” For example, the font faces “Helvetica” and “Helvetica Bold” are both considered to be part of the family named “Helvetica.”

To find out which fonts are available on a particular computer, call the getAvailable- Font Family Names method of the GraphicsEnvironmentclass. The method returns an array ofstrings that contains the names of all available fonts. To obtain an instance of the

Graphics Environment class that describes the graphics environment of the user’s system, use the static getLocalGraphicsEnvironmentmethod. Thus, the following program prints the names of all fonts on your system:

On one system, the list starts out like this:
Abadi MT Condensed Light

Font face names can be trademarked, and font designs can be copyrighted in some jurisdictions.

Thus, the distribution of fonts often involves royalty payments to a font foundry. Of course, just as there are inexpensive imitations of famous perfumes, there are lookalikes for name-brand fonts. For example, the Helvetica imitation that is shipped with Windows is called Arial.

To establish a common baseline, the AWT defines five logical font names:

These names are always mapped to fonts that actually exist on the client machine. For example, on a Windows system, SansSerif is mapped to Arial.

In addition, the Sun JDK always includes three font families named “Lucida Sans,” “Lucida Bright,” and “Lucida Sans Typewriter.”

To draw characters in a font, you must first create an object of the class Font. You specify the font face name, the font style, and the point size. Here is an example of how you construct a Font object:

The third argument is the point size. Points are commonly used in typography to indicate the size of a font. There are 72 points per inch.

You can use a logical font name in the place of a font face name in the Font constructor. You specify the style (plain, bold, italic, or bold italic) by setting the second Font constructor argument to one of the following values:

NOTE: The mapping from logical to physical font names is defined in the fontconfig.propertiesfile in the jre/lib subdirectory of the Java installation.

You can read font files in TrueType or PostScript Type 1 formats. You need an input stream for the font—typically from a file or URL.

Then call the static Font.createFontmethod:

The font is plain with a font size of 1 point. Use the deriveFontmethod to get a font of the desired size:

CAUTION: There are two overloaded versions of the deriveFontmethod. One of them (with a float parameter) sets the font size, the other (with an intparameter) sets the font style.

Thus, f1.deriveFont(14) sets the style and not the size! (The result is an italic font because it happens that the binary representation of 14 sets the ITALIC bit but not the BOLD bit.)

The Java fonts contain the usual ASCII characters as well as symbols. For example,if you print the character 'u2297' in the Dialog font, then you get a ⊗ character. Only those

symbols that are defined in the Unicode character set are available. Here’s the code that displays the string “Hello, World!” in the standard sans serif font on your system, using 14-point bold type:

Next, let’s center the string in its component rather than drawing it at an arbitrary position. We need to know the width and height of the string in pixels. These dimensions depend on three factors:

  • The font used (in our case, sans serif, bold, 14 point);
  • The string (in our case, “Hello, World!”); and
  • The device on which the font is drawn (in our case, the user’s screen).

To obtain an object that represents the font characteristics of the screen device, you call the get Font Render Context method of the Graphics2D class. It returns an object of the Font -Render Context class. You simply pass that object to the get String Bounds method of the Font

The getStringBoundsmethod returns a rectangle that encloses the string.

To interpret the dimensions of that rectangle, you should know some basic typesettingterms. The baseline is the imaginary line where, for example, the bottomof a character like “e” rests. The ascent 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 character. The descent is the distance from the baseline to a descender, which is the lower portion of a letter like “p” or “g.”

Typesetting terms illustrated

Typesetting terms illustrated

Leading is the space between the descent of one line and the ascent of the next line. (The term has its origin from the strips of lead that typesetters used to separate lines.) The height of a font is the distance between successive baselines, which is the same as descent + leading + ascent.

The width of the rectangle that the get String Bound smethod returns is the horizontal extent of the string. The height of the rectangle is the sum of ascent, descent, and leading. The rectangle has its origin at the baseline of the string. The top y-coordinate of the rectangle is negative. Thus, you can obtain string width, height, and ascent as follows:

If you need to know the descent or leading, you need to use the get Line Metrics method of the Font class. That method returns an object of the Line Metrics class, which has methods to obtain the descent and leading:

The following code uses all this information to center a string in its surrounding component:

To understand the centering, consider that getWidth() returns the width of the component. A portion of that width, namely, bounds.getWidth(), is occupied by the message string. The remainder should be equally distributed on both sides. Therefore, the blank space on each side is half the difference. The same reasoning applies to the height.

NOTE: When you need to compute layout dimensions outside the paint Component method, you can’t obtain the font render context from the Graphics 2D object. Instead, call the getFont-Metrics method of the JComponent class and then call get Font Render Context.

To show that the positioning is accurate, the sample program also draws the baselineand the bounding rectangle. Figure below shows the screen display.

Drawing the baseline and string bounds

Drawing the baseline and string bounds

  • Font(String name, int style, int size)
    creates a new font object.
  • String getFontName()
    gets the font face name (such as “Helvetica Bold”).
  • String getFamily()
  • String getName()
    gets the logical name (such as “SansSerif”) if the font was created with a logical font name; otherwise, gets the font face name.
  • Rectangle 2D get String Bounds(String s, FontRenderContext context)

returns a rectangle that encloses the string. The origin of the rectangle falls on the baseline. The top y-coordinate of the rectangle equals the negative of the ascent.

The height of the rectangle equals the sum of ascent, descent, and leading. The width equals the string width.

  • LineMetricsgetLineMetrics(String s, Font Render Context context)

returns a line metrics object to determine the extent of the string.

  • Font deriveFont(int style)
  • Font deriveFont(float size)
  • Font deriveFont(int style, float size)

returns a new font that equals this font, except that it has the given size and style.


  • float getAscent()
    gets the font ascent—the distance from the baseline to the tops of uppercase characters.
  • float getDescent()
    gets the font descent—the distance from the baseline to the bottoms of descenders.
  • float getLeading()
    gets the font leading—the space between the bottom of one line of text and the top of the next line.
  • float getHeight()
    gets the total height of the font —the distance between the two baselines of text
(descent + leading + ascent).


  • Font getFont()
  • void setFont(Font font)
    gets or sets the current font. That font will be used for subsequent text-drawing operations.
  • voiddrawString(String str, int x, int y)
    draws a string in the current font and color.
  • FontRenderContextgetFontRenderContext()
    gets a font render context that specifies font characteristics in this graphics context.
  • voiddrawString(String str, float x, float y)
    draws a string in the current font and color.



  • FontMetricsgetFontMetrics(Font f)
    gets the font metrics for the given font. The FontMetricsclass is a precursor to the LineMetricsclass.


  • FontRenderContextgetFontRenderContext() 1.2

gets a font render context for the font.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics