Java Reference
In-Depth Information
Display 18.21
Using
drawString
(part 3 of 3)
R
ESULTING
GUI
(After clicking the button)
Fonts
The program in Display 18.21 illustrates how the font for the method
drawString
is
set. That program sets the font with the following line in the definition of the method
paint
:
setFont
g.setFont(fontObject);
In that program
fontObject
is a private instance variable of type
Font
.
Font
is a class
in the
java.awt
package. Objects of the class
Font
represent fonts.
In Display 18.21 the variable
fontObject
is set using a constructor for the class
Font
. The initial font is set as part of the instance variable declaration in the following
lines taken from Display 18.21:
private
Font fontObject =
new
Font("SansSerif", Font.PLAIN, POINT_SIZE);
The constructor for the class
Font
creates a font in a given style and size. The first
argument, in this case
"SansSerif"
, is a string that gives the name of the font (that is,
the basic style). Some typical font names are
"Times"
,
"Courier"
, and
"Helvetica"
.
You may use any font currently available on your system. Java guarantees that you will
have at least the three fonts
"Monospaced"
,
"SansSerif"
, and
"Serif"
. To see what
these fonts look like on your system, run the program
FontDisplay.java
on the
accompanying CD. It will produce the window shown in Display 18.22.
Most font names have no real meaning. The names just sounded right to the cre-
ator. However, the terms “Serif,” “Sans Serif,” and “Monospaced” do mean something,
which may help you keep the names of the three guaranteed fonts clear in your mind.
Serifs
are those small lines that sometimes finish off the ends of the lines in letters. For
example, S has serifs (at the two ends of the curved line), but
S
does not have serifs.
The
"Serif"
font will always have these decorative little lines.
Sans
means without, so
Font
extra code
on CD