Java Free Tutorial

Web based School

Chapter 16

Using Fonts and Color in Applets

A famous catchphrase from the television show Saturday Night Live during the 1980s was, "It's not how you feel, but how you look...and darling, you look MAH-ve-lous." The quote epitomized the philosophy of Fernando, comedian Billy Crystal's eternally tan and impeccably groomed celebrity. Regardless of what was going on in his life, as long as his hair was styled properly and he was dressed for the occasion, everything was copacetic. After all, though Fernando hadn't been in a hit movie since Won Ton Ton, the Dog Who Saved Hollywood, he still looked good. Correction: He looked MAH-ve-lous.

If you're interested in making your Java applets look MAH-ve-lous, you should know about the Font and Color classes. No self-respecting applet would be seen in public without them. With these classes, you can present text in several different fonts and sizes and change the colors of text, graphics, and other elements.

One of the principles of object-oriented programming is to make an object work for itself, and the Font and Color objects follow this rule. They store all the information that's needed to display a font or change a color, and they can handle other related tasks that are required. The following topics will be covered during this hour:

  • Using fonts in your applets

  • Setting a font's style and size

  • Choosing a font

  • Displaying colors in applets

  • Using the color constants

  • Setting up the background color

  • Using RGB values to choose colors

  • Using HSB values to choose colors

  • Creating special text effects using colors

Using the Font Class

There are three things you need to know about a font in order to display it:

  • The typeface of the font: Helvetica, Courier, Dialog, Times Roman, or others

  • The style of the font: bold, italic, or plain

  • The size of the font, in points

Before you can display text in a certain typeface, style, and point size, you need to create a Font object that holds this information. The following statement creates a 12-point Times Roman italic Font object:

Font currentFont = new Font("TimesRoman", Font.ITALIC, 12);

The typeface that you can select may vary depending on the system you're using. The current release of the Java Developer's Kit for Windows 95 includes Helvetica, Courier, Dialog, Dialog Input, and Times Roman.

You choose the style of the font by using one or more constant variables. Specifying the style as Font.PLAIN makes it nonbold and nonitalic, Font.BOLD makes it bold, and Font.ITALIC makes it italic. To combine bold and italic, use Font.BOLD+Font.ITALIC, as in the following code:

Font headlineFont = new Font("Courier", Font.BOLD+Font.ITALIC, 72);

The last argument specifies the point size of the font. To see a simple example of using fonts in an applet, open your word processor and create a new file called Enter the text of Listing 16.1 and save the file.

Listing 16.1. The full text of

 1: import java.awt.*;
 3: public class Fonts extends java.applet.Applet {
 5:     public void paint(Graphics screen) {
 6:         Font currentFont = new Font("TimesRoman", Font.PLAIN, 20);
 7:         screen.setFont(currentFont);
 8:         screen.drawString("If I've said it once, I've said it a thousand 	 9:         times, darling,", 5, 50);
10:         currentFont = new Font("TimesRoman", Font.ITALIC, 40);
11:         screen.setFont(currentFont);
12:         screen.drawString("you look MAH-VE-LOUS", 5, 80);
13:     }
14: } 

After you compile the file with the javac compiler tool, you need to create a Web page that contains the applet. Create a new file in your word processor called Fonts.asp and enter the text of Listing 16.2.

Listing 16.2. The full text of Fonts.asp.

1: <applet code="Fonts.class" height=125 width=450>
2: </applet> 

Save this file and then load this page into the appletviewer tool by using the following command:

appletviewer Fonts.asp

The output should resemble Figure 16.1.

Figure 16.1. The output of the Fonts applet.

Using the Color Class

The simplest way to use a color in a Java program is to use one of the constant variables from the Color class. You can use the following constants: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, and yellow.

In an applet, you can set the background color of the applet window using these constants. The following is an example:


When you want to display text of a certain color or draw other graphics in different colors, you have to use a method that sets up the current color. You can do this from within the paint() method of an applet by using a setColor() method, as in the following:

public void paint(Graphics screen) {
    screen.drawString("Go, Buccaneers!", 5, 50);

Unlike the setBackground() method, which is inherited directly from the Applet class, the setColor() method must be used on an object that can handle a color change. The preceding example shows the setColor() method of the screen object being used to change the current color of the applet window.

Other Ways to Choose Colors

To use a color not included in the 13 constant variables, you must specify the color's RGB or HSB values. RGB, which stands for Red Green Blue, defines a color by the amount of red, green, and blue that is present in the color. Each value ranges from 0, which means there is none of that color, to 255, which means the maximum amount of that color is present. Most graphics editing and drawing programs will identify a color's RGB values.

If you know a color's RGB values, you can use it to create a Color object. For example, an RGB value for dark red is 235 red, 50 green, and 50 blue, and an RGB value for light orange is 230 red, 220 green, and 0 blue. The following is an example of an applet that displays dark red text on a light orange background:

import java.awt.*;

public class GoBucs extends java.applet.Applet {

    public void init() {
        Color lightOrange = new Color(230, 220, 0);

    public void paint(Graphics screen) {
        Color darkRed = new Color(235, 50, 50);
        screen.drawString("Go, Buccaneers!", 5, 50);

Dark red on a light orange background isn't much more attractive on a Java applet than it is on the National Football League's Tampa Bay Buccaneers. Using RGB values enables you to select from more than 16.5 million possible combinations, although most computer monitors can only offer a close approximation for most of them. For guidance on whether light-light-light-semidark-midnight-blue goes well with medium-light-semidark-baby-green, purchase a copy of the upcoming Learn Color Sense While Waiting in Line at This guidestore from Publishing.

Another way to select a color in a Java program is the HSB system, which stands for Hue Saturation Brightness. Each of these is a floating-point number that ranges from 0.0 to 1.0. The HSB system isn't as commonly supported in graphics software, so you won't be using it as often in your programs as you use RGB values. However, one thing HSB values are convenient for is changing a color's brightness without changing anything else about the color. You'll see an example of this use and an example of using HSB values to choose a color in this hour's workshop.

Workshop: Displaying a Danger Message

You can use Java applets to present news headlines and other information in different ways. One special effect you might see on a Web page is text that fades to black. You also might see the reverse--text that brightens from black to white. This hour's workshop uses the Font and Color classes to create text that cycles in brightness from dark to bright. The text looks like an alert about impending danger, so the applet will be called Danger.

To make the applet more useful, the text of the warning will be set from a parameter on a Web page. The text that will be used in this example warns of a "Core breach in Sector 12," but you can substitute other threatening text of similar length.

If you're at a secure place in your life right now and can't think of anything suitably menacing, feel free to choose one of the following:

  • "Mother-in-law wants to visit"

  • "Boss approaching"

  • "Dallas Cowboys scheduled to play here"

  • "We have no bananas today"

  • "No hamburger--cheeseburger"

Create a new file in your word processor called Each section of the applet will be described as you enter it. Begin with the following statements:

import java.awt.*;

public class Danger extends java.applet.Applet {
    String text = "No text has been specified";
    float hue = (float) 0.5;
    float saturation = (float) 0.8;
    float brightness = (float) 0.0;
    Font textFont = new Font("Dialog", Font.BOLD, 20);
    int textX;

The program begins like most applets that you will create. The java.awt classes, such as Font, Color, and FontMetrics, are made available for use in this program with the import statement. The class statement defines Danger as a subclass of the Applet class, as all applets must be.

The next several lines define variables and objects that will be used during the program. The string variable text is created with a default value, and it will be used to store the text that should be displayed on-screen. Three floating-point variables are used to store values for a color using its Hue Saturation Brightness (HSB) ratings. The (float) portion of each line converts the value that follows it into a floating-point number. This conversion must be done because the hue, saturation, and brightness variables must be of type float.

The text of the applet will be displayed in 20-point Dialog bold. In order to do this, you need to create a Font object to store that font's values. The Font object called textFont is created for this purpose. Finally, the integer variable textX will be used when you're centering text from left-to-right on the screen.

After inserting a blank line, continue entering the Danger program by entering the init() method of the applet:

public void init() {
    String paramName = getParameter("TEXT");
    if (paramName != null)
        text = paramName;
    FontMetrics fm = getFontMetrics(textFont);
    textX = size().width / 2 - fm.stringWidth(text) / 2;

The init() method is handled once when the applet is first run, and then it is never handled again. It's a good place to set up some things that weren't set up when variables and objects were created. The first thing that happens in this method is the background of the applet is set to black by using the setBackground() method inherited by Danger from the Applet class.

Next, the parameter called TEXT is retrieved from the Web page that contains this applet. If no parameter is found, the default text stored in text will be displayed. Otherwise, the text specified by the parameter will be stored in text.

The FontMetrics class measures how wide a line of text will appear when it is displayed. Using the stringWidth() method of FontMetrics and the applet's size() method, you can center text on-screen. The textX variable stores the horizontal position where the text should be displayed.

Now continue by entering the paint() method of your class, which is called whenever the display on-screen needs to be updated. Leave a blank line after the init() method and enter the following:

public void paint(Graphics screen) {
    Color textColor = Color.getHSBColor(hue, saturation, brightness);
    screen.drawString(text, textX, 30);
    brightness += 0.05;
    if (brightness > 1) {
        brightness = (float) 0.0;

The paint() method takes a Graphics object called screen as an argument. This object holds all the information needed to display something on-screen, and it has several methods you'll use.

The Color object called textColor is created using the HSB variables to select the color. The textColor object then becomes the current display color using the setColor() method of screen.

Using the drawString() method of screen, the variable text is displayed at the (x,y) position of textX and 30. The color of the text is the current display color. After the text has been displayed, a pause() method is called with an argument of 250,000. You'll see what this method does when you add it to your program.

In order for the text to change in brightness, you have to change the value of the brightness variable. The program increases the variable .05 (a 5 percent change), and if the variable has reached the maximum brightness of 1.0, it is reset to 0.0. Whenever brightness must be reset to 0.0, the program calls the pause() method.

The last thing that takes place in the paint() method is the repaint(); statement. You use this statement any time you need to redraw the screen because something has changed. Because the brightness variable has changed, you know there's a need to redisplay the text at the new brightness. The repaint() statement causes the paint() method to begin again.

The paint() method handles most of the work that takes place during the Danger applet. All you have left to add are two short methods called update() and pause(). Enter a blank line at the end of your program, and then continue with the following statements:

public void update(Graphics screen) {

void pause(int duration) {
    for (int pause = 0; pause < duration; pause++);


The update()method is one of the methods that normally works behind the scenes as an applet runs. It is handled any time the screen needs to be repainted or the repaint() statement is used. The update() method clears the screen and calls on paint() to do its work. However, clearing the screen when you're changing graphics or text often causes things to flicker badly in a Java program. In this code, you're overriding the update() method so it does not clear the screen at all, which will improve the quality of your applet's display. You'll learn more about this procedure during Chapter 18, "Creating Animation."

The last thing in your applet is the pause() method, which takes an argument called duration. The method runs an empty for loop ranging from 0 to the value of duration. This loop causes the program to pause. The higher the value of duration, the longer the pause. When you are displaying changing graphics or text, you might need pauses of some kind to prevent things from changing too quickly. This pause() method is one way to create these pauses.

Save the file, which should resemble Listing 16.3. The only difference might be in the way you have indented methods and other statements. That does not have to be changed in order for the program to run, but indentation and other spacing can make a program easier to understand.

Listing 16.3. The full text of

 1: import java.awt.*;
 3: public class Danger extends java.applet.Applet {
 4:    String text = "No text has been specified";
 5:    float hue = (float) 0.5;
 6:    float saturation = (float) 0.8;
 7:    float brightness = (float) 0.0;
 8:    Font textFont = new Font("Dialog", Font.BOLD, 20);
 9:    int textX;
11:    public void init() {
12:        setBackground(;
13:        String paramName = getParameter("TEXT");
14:        if (paramName != null)
15:            text = paramName;
16:        FontMetrics fm = getFontMetrics(textFont);
17:        textX = size().width / 2 - fm.stringWidth(text) / 2;
18:    }
20:    public void paint(Graphics screen) {
21:        Color textColor = Color.getHSBColor(hue, saturation, brightness);
22:        screen.setColor(textColor);
23:        screen.setFont(textFont);
24:        screen.drawString(text, textX, 30);
25:        pause(250000);
26:        brightness += 0.05;
27:        if (brightness > 1) {
28:            brightness = (float) 0.0;
29:            pause(250000);
30:        }
31:        repaint();
32:    }
34:    public void update(Graphics screen) {
35:        paint(screen);
36:    }
38:    void pause(int duration) {
39:        for (int pause = 0; pause < duration; pause++);
40:    }
42: } 

After compiling the file with the javac compiler tool, you need to create a Web page that contains the Danger applet. Create a new file with your word processor called Danger.asp, and enter the text of Listing 16.4 into the file.

Listing 16.4. The full text of Danger.asp.

1: <applet code="Danger.class" height=60 width=400>
2: <param name="TEXT" value="Core breach in Sector 12">
3: </applet> 

You can change the value in Line 2 to any other menacing sounding text, as long as it is similar in size to Core breach in Sector 12. Use the appletviewer tool to view the Web page with the following command:

appletviewer Danger.asp

Figure 16.2 shows the output of the Danger applet.

Figure 16.2. A screen capture of the Danger applet as it runs with the appletviewer tool.


Now that you can use Font and Color objects in your programs to change the color scheme, you can no longer feign ignorance when it comes to designing an attractive applet. By using fonts and color instead of sticking to the familiar black text on a light gray background, you can draw more attention to elements of your programs and make them more compelling for users. You also, of course, can write programs that look MAH-ve-lous. It's what Fernando would want you to do.


Q Is there a limit to the point size that can be used for text?

The limiting factor is the height and width of your applet window or the part of an applet the text is supposed to be displayed in. Point sizes typically range from 9-point text for small lines that are readable to 48-point text for large headlines. Choosing the right size depends on the font typeface as well as the size, so it's largely a matter of trial and error.

Q What happens if a color defined in a Java program can't be displayed on the monitor of someone displaying the program? For example, if my monitor is set to display only 256 colors, what will occur if I choose one of the 16.5 million colors that isn't in those 256?

When a monitor can't display a color selected with a setColor() or setBackground() method, it shows the closest existing color as a substitute. An example of this kind of substitution is the Danger applet, which runs differently depending on the number of colors that can be shown as the text cycles from black to light blue to white.


Test whether your font and color skills are MAH-ve-lous by answering the following questions.


1. Which one of the following is not a constant used to select a color?

(a) Color.cyan
(b) Color.teal

When you change the color of something and redraw it on an applet window, what must you do to make it visible?

(a) Use the drawColor() method.
(b) Use the repaint() statement.
Do nothing.

What do the initials HSB stand for?

(a) Hue Saturation Brightness
(b) Hue Shadows Balance
Lucy in the Sky with Diamonds


1. b.

b. The call to repaint() causes the paint() method to be manually called.

a. If c were the right answer, you could use colors that would only be visible years later during flashbacks.


To further explore the spectrum of possibilities when using fonts and color in your programs, do the following activities:

  • Remove the update() method from the Danger applet to see what effect it has on the quality of the display.

  • Add a way to specify the background of the Danger applet by sending parameters for the RGB values of the desired background color.