devxlogo

Master Font Manipulation in Java

Master Font Manipulation in Java

hether you think very much about fonts or not, as an application user, you are constantly interacting with and manipulating fonts. Particularly in word processing programs, where it’s common to change typestyles and typefaces for different parts of your document.

So too, the ability to change typestyles and typefaces is useful as an application programmer. As a simple example, think of the “About” screen, which most every program has. It is common to see the program name in large text, to help it stand out, and legal jargon and copyright notices in smaller sized text. You can see this in Microsoft Word’s Help/About menu.

When writing computer programs, you want your user interface to be as intuitive as possible. This means you will use radio buttons and checkboxes and other visual components that your end users already understand. However, it also means that you want written information to stand out as clearly as possible.

As well as varying the size of text, you may want to enhance specific words?by rendering them in bold, perhaps, or italics?to draw readers’ attention.

Also, you might want to consider how the reader will use the textual information you have provided. For instance, for information displayed on the screen, you might wish to use a sans-serif font such as Arial. However, for information that the user will print out from your application onto paper, you might wish to use a serif font such as Times Roman. These simple changes can help your user read and digest the information you want to convey.

So, with that in mind, let’s see how you can manage your textual information in Java, to enhance your own applications.

Anatomy of a Java Font Object
In Java, fonts are represented by instances of the java.awt.Font class. A Font object comprises three parts: a font name (e.g. serif), style identifier (e.g. bold) and a point size (e.g. 10).

As with any Java object, we can create an instance of the Font object in memory at any time. Of course, a visual item like a font is only meaningful if we actually apply it to something displayed on the screen, such as the text on a button or a label. Just because we can create a font object?as in the following examples?doesn’t necessarily mean anything is seen on the screen.

Here are some examples of declaring fonts:

Font littleFont = new Font("Monospaced", Font.PLAIN, 10);Font bigFont = new Font("Serif", Font.BOLD, 24);

In word processing programs we’re accustomed to selecting specific fonts, by name, such as Arial, Garamond, Times New Roman, etc. However, because it was designed to run on as many different operating systems as possible, Java does not use specific font names because those names may be specific to a particular system. Rather, it uses symbolic names that refer to a particular type of font?”Monospaced” and “Serif.” These names are translated to a specific font on the executing computer by the Java interpreter.

Table 1 describes the five font classes that are available.

Table 1. The Five Font Classes

Serif

Contains serifs on the edges of characters, e.g. Times Roman

SansSerif

A font without serifs, e.g. Helvetica

Monospaced

A non-proportional font, such as Courier, where the letter “i” takes as much space as the letter “w”

Dialog

A font used for dialog screens, such as opening a file

DialogInput

A font used for user input on dialog screens, such as typing in a file name

The way the Java interpreter maps the font is through a file called fonts.properties. This file will easily be found in the lib subdirectory of your Java development environment, whether you’re using Sun’s JDK or a third-party Java implementation such as Borland JBuilder.

There are three style identifiers, namely PLAIN, BOLD, and ITALIC. These are constant values that belong to the Font object. You can apply both BOLD and ITALIC to a font at the same time. (Actually, you can apply any combination, but as you will appreciate, PLAIN has no effect unless it is used by itself.)

To actually use a Font object, you simply specify it as an argument to the setFont() method of any component?such as a button?or to an applet’s Graphics object, which is used to paint the canvas. Any subsequent text-drawing command for that applet, such as drawString(),will use the specified font.

A second useful class is java.awt.FontMetrics. This object can give us detailed size and spacing information about text that has been rendered in a specific font. As you might imagine, different systems will have different fonts available, and so careful programmers will never presume that a word will take up the exact same amount of space on one screen that it will on another. So, FontMetrics is useful for retrieving information about how the font you choose is sized on a specific system.

The Graphics object has a getFontMetrics() method that gives us the information we need about how the font is sized for the font currently in use:

public void paint (Graphics g){  FontMetrics fm = g.getFontMetrics ();  ...}

Listing 1 is a Java applet that draws a word in a particular font and then draws reference lines showing certain characteristics, namely, the font’s baselines and its descent and ascent properties (described below).

Figure 1: Running the FontShow applet in Sun’s AppletViewer.
Figure 2 : Running the FontShow applet in Internet Explorer.

The applet requires two parameters be passed to it: “word” (the word to be displayed) and “fontname” (the font style to be used). Once you’ve written the code to pass these parameters, try entering different values in the HTML page (see Listing 2) and re-running the applet.

The program might look a bit complicated, but there’s not really much to it. Most of the code is in the applet’s paint() method, which merely sets the font, draws our word, and overlays a few lines that help illustrate some of the font’s metrics. You can make use of the metrics information to format a screen without making any prior assumptions about the font.

By default, text is rendered above and to the right of the coordinates specified in the drawString() method. If that starting point is the origin of a coordinate system, then the axes are the baselines of the font, and here these lines are drawn in white.

In the sample application the ascent, where characters stretch above the baseline (such as the letter “l”) is shown with a green line. Some fonts also have parts of letters that fall below the baseline (such as the letter “g”). This is called the descent and is shown in red.

The FontMetrics object has getMaxAscent() and getMaxDescent() methods that yield the lengths of the ascent and descent. The applet centers our word vertically in the display area by averaging the influence of the ascent and descent. FontMetrics also has a useful stringWidth() method which advises the width of the string when rendered in this font?we use this information for centering our word horizontally.

There are three other FontMetrics methods that I haven’t used here?getLeading() gives the vertical spacing between multiple lines in the font, getHeight() gives the total line height (namely, ascent + descent + leading) in the font, and getMaxAdvance() returns the maximum character width of any character in the font.

That’s really all there is to font handling in Java?or, at least as far as the native language goes. Sun has developed more font handling features in its new 2D graphics API libraries, including portable fonts. With portable fonts the font itself is actually taken and bundled into the Java program. This guarantees that the font used will be exactly the one that you selected, regardless of the operating system. However, this is a separate download and is not yet in widespread use or widely supported by Web browsers.

Listings 3 and 4 contain a second applet, AllFonts.java, which lists a sample of each font class. You can use this list to see the appearance of a given message in different fonts and across different operating systems.

Figure 3: Running the AllFonts applet in Sun’s AppletViewer.Pictured is a sample run of the AllFonts applet, running in Sun’s AppletViewer on a Sun Solaris computer.
Figure 4 : Running the AllFonts applet in Internet Explorer.Pictured is a sample run of the AllFonts applet, running in Internet Explorer on a Windows PC.

Less Can Be More
If you can apply everything demonstrated in this article in a live application, then you can consider yourself a Java font master! You should have all the information you need to change the type and style of fonts in your own Java programs and applets to enhance your presentation and help the user.

However, do use this wisely; overuse of font styles is distracting. Many of us remember the rise of desktop publishing back in the ’80s and all the kitsch fliers, brochures, and other documents that tried to cram as many possible font changes as possible into a single page. The purpose of changing your font type and style is to enhance communications, making your programs clearer and more intuitive. So, keep in mind then, that too many font changes can have the opposite effect.

One thing I like to do when considering a new visual technique is to explore how other programmers have implemented it. For example, if you’re making a menu bar, it makes sense to follow the established conventions of software manufacturers who generally use the menu names “File,” “Edit,” and “View” and always put the “Help” menu at the far right.

You can follow similar logic when selecting fonts. Where have other developers varied the font type or style? Did they use a particular type of font for screen information as opposed to print information? The more your application conforms to commonly-accepted standards, the more natural and intuitive your users will find it.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist