0% found this document useful (0 votes)
62 views6 pages

Hour 21. Using Fonts and Color

The document discusses using fonts and colors in Java programs. It describes how to use the Font and Color classes to specify fonts, font styles, sizes, and colors. The Font class is used to define fonts by specifying the typeface, style (bold, italic, etc.), and size. The Color class contains constants for common colors and can be used to specify colors by RGB or HSB values. An example program draws text in different fonts and colors on a panel to demonstrate using fonts and setting colors.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views6 pages

Hour 21. Using Fonts and Color

The document discusses using fonts and colors in Java programs. It describes how to use the Font and Color classes to specify fonts, font styles, sizes, and colors. The Font class is used to define fonts by specifying the typeface, style (bold, italic, etc.), and size. The Color class contains constants for common colors and can be used to specify colors by RGB or HSB values. An example program draws text in different fonts and colors on a panel to demonstrate using fonts and setting colors.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Hour 21.

Using Fonts and Color

A catch phrase 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 character. Regardless of what was going on
in Fernando's life, as long as his hair was styled properly and he was dressed for the occasion, everything
was copacetic because he still looked good. Correction: MAH-ve-lous.

If you're interested in making your Java programs look MAH-ve-lous, you should know about the Font and
Color classes. No self-respecting program would be seen in public without them. You'll learn about these
classes during this hour as the following topics are covered:

 Using fonts in your programs

 Setting a font's style and size

 Displaying colors

 Using the color constants

 Setting up the background color

 Using sRGB values to choose colors

 Using HSB values to choose colors

 Creating special text effects using colors

Using the Font Class

Colors and fonts are represented in Java by the Color and Font classes, which both belong to the
java.awt package. 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.

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

 The typeface of the font: Either a descriptive name (Dialog, DialogInput, Monospaced,
SanSerif, or Serif) or an actual font name (such as Arial, Courier New, or Times New Roman)
 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 serif italic Font object:

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

When selecting a typeface, it's better to choose one of the descriptive names: Serif, SanSerif, and
Monospaced. This enables the system running the program to designate one of its own fonts that fits the
description.

You can, however, refer to specific fonts, which will only be used if they are installed on the computer of the
person running your program.

You choose the style of the font by using one or more constant variables. Specifying the style as
Font.PLAIN makes it non-bold and non-italic, 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 New", Font.BOLD+Font.ITALIC, 72);

The last argument specifies the point size of the font.

There are several ways to make use of fonts in a Java program:

 On a graphical user interface, you can call a component's setFont ( Font ) method, which

designates the font as the one that will be used on all subsequent text that is displayed (until the font is
changed).

 On a container such as a panel, you can override the paintComponent ( Graphics ) method
and work with the Graphics object to set and display fonts.

 On an applet window, you can override the paint( Graphics ) method as you did on Hour 17,

"Creating Interactive Web Programs."

The first project you undertake during this hour draws text on a panel. This class uses the second option for
using fonts—overriding a panel's paintComponent() method. Open your word processor and create a
new file called Player.java, entering the text of Listing 21.1 in the file.

Example 21.1. The Full Text of Player.java

1: import java.awt.*;
2: import javax.swing.*;
3:
4: public class Player extends JFrame {
5: public Player() {
6: super("Player");
7: setSize(244, 286);
8: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9: PlayerPanel fp = new PlayerPanel();
10: Container pane = getContentPane();
11: pane.add(fp);
12: setContentPane(pane);
13: setVisible(true);
14: }
15:
16: public static void main(String[] arguments) {
17: Player frame = new Player();
18: }
19: }
20:
21: class PlayerPanel extends JPanel {
22: public void paintComponent(Graphics comp) {
23: super.paintComponent(comp);
24: Graphics2D comp2D = (Graphics2D)comp;
25: int width = getSize().width;
26: int height = getSize().height;
27: Font currentFont = new Font("Dialog", Font.BOLD, 18);
28: comp2D.setFont(currentFont);
29: comp2D.drawString("ARMANDO BENITEZ", width - 185, height - 30);
30: currentFont = new Font("Dialog", Font.ITALIC, 12);
31: comp2D.setFont(currentFont);
32: comp2D.drawString("pitcher", width - 170, height - 10);
33: currentFont = new Font("Dialog", Font.PLAIN, 12);
34: comp2D.setFont(currentFont);
35: comp2D.drawString("NEW YORK METS", width - 110, height - 10);
36: }
37: }

After you compile the file with javac or another compiler, run the application. The program should

resemble Figure 21.1.


Figure 21.1 Running the Player application.

The Player application is a frame that contains a panel where several strings will be drawn using different
font objects. All of the work involving fonts takes place in the FontPanel class, which is defined in Lines

22–35.

The paintComponent( Graphics ) method of a container functions the same as the paint(
Graphics ) method in an applet. This method is called automatically whenever the container needs to be
redrawn.

The first thing that takes place in the method is the call to super.paintComponent(), which calls the

method in the superclass to make sure that everything is set up correctly before you begin drawing in the
panel.

Next, to make use of Java2D, the Graphics object is used to create a Graphics2D object called
comp2D in Line 24. All subsequent font and drawing methods will be called on this object.

A Font object is created in Line 27 that represents a Dialog, bold 18-point font. The setFont() method
of comp2D is called to make this the current font.

Next, the drawString( String ) method of comp2D is called with the text of a string to display. The

same thing happens with different fonts and strings in Lines 30–35.

The Player application uses the width and height of the panel to determine where the text should be

drawn. The first text, the name of New York Mets closer Armando Benitez, is displayed 185 pixels to the
left of the right edge and 30 pixels above the bottom edge. If you resize the application window, the text will
move accordingly.

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:
setBackground(Color.orange);

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 paintComponent() method of a
container by using a setColor() method, as in the following:

public void paintComponent(Graphics comp) {


Graphics2D comp2D = (Graphics2D)comp;
comp2D.setColor(Color.orange);
comp2D.drawString("Go, Buccaneers!", 5, 50);
}

Unlike the setBackground() method, which can be called directly on a container such as a panel or
applet, the setColor() method must be used on an object that can handle a color change. The
preceding example shows the setColor() method of the comp2D object being used to change the

current color of the container window.

Other Ways to Choose Colors

To use a color not included in the 13 constant variables, you must specify the color's sRGB or HSB values.
sRGB, which stands for Standard 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 sRGB values.

If you know a color's sRGB value, you can use it to create a Color object. For example, an sRGB value

for dark red is 235 red, 50 green, and 50 blue, and an sRGB value for light orange is 230 red, 220 green,
and 0 blue. The following is an example of a panel that displays light orange text on a dark red background:

import java.awt.*;
import javax.swing.*;

public class GoBucs extends JPanel {


Color lightOrange = new Color(230, 220, 0);
Color darkRed = new Color(235, 50, 50);

public void paintComponent(Graphics comp) {


Graphics2D comp2D = (Graphics2D)comp;
comp2D.setColor(darkRed);
comp2D.fillRect(0, 0, 200, 100);
comp2D.setColor(lightOrange);
comp2D.drawString("Go, Buccaneers!", 5, 50);
}
}

This example calls the fillRect() method of Graphics2D to draw a filled-in rectangle using the

current color. You will learn more about this method on Hour 23.

Light orange on a dark red background isn't much more attractive on a Java program than it was on the
National Football League's Tampa Bay Buccaneers, which might be the reason they now wear brass-and-
pewter uniforms. Using sRGB 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 burnt-semidark-midnight-blue goes well with medium-light-faded-baby-green,
purchase a copy of the upcoming Sams Teach Yourself Color Sense While Waiting in Line at This
Bookstore.

Another way to select a color in a Java program is the HSB system, which stands for Hue Saturation
Brightness. Each of these values is represented by 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 sRGB 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.

Summary

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 program. 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.

By combining these features, you're now one step closer to writing programs that look MAH-ve-lous.

You might also like