Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

WHAT YOU’LL LEARN IN
THIS HOUR:
.Setting the font and color
of text
.Setting up a container’s
background color
.Drawing lines,rectangles,
and other shapes
.Drawing GIF and JPEG
graphics
.Drawing filled and unfilled
shapes

During this hour, you learn how to turn Swing containers—the plain gray
panels and frames that hold graphical user interface (GUI) components—
into an artistic canvas on which you can draw fonts, colors, shapes, and
graphics.


Using the Font Class


Colors and fonts are representedin Java by the Colorand Fontclasses in
the java.awtpackage. With these classes, you can present text in different
fonts and sizes and change the color of text and graphics. Fonts are created
with the Font(String, int, int)constructor, which takes three argu-
ments:


. The typeface of the font as either a generic name (“Dialog,”
“DialogInput,” “Monospaced,” “SanSerif,” or “Serif”) or an actual
font name (“Arial Black,” “Helvetica,” or “Courier New”)
. The style as one of three class variables: Font.BOLD, Font.ITALIC, or
Font.PLAIN
. The size of the font in points


The following statement creates a 12-point italic Serif Fontobject:


Font current = new Font(“Serif”, Font.ITALIC, 12);


If you use a specific fonts rather than one of the generic ones, it must be
installed on the computer of users running your program. You can com-
bine the font styles by adding them together, as in the following example:


Font headline = new Font(“Courier New”, Font.BOLD+ Font.ITALIC, 72);


HOUR 23


Creating Java2D Graphics

Free download pdf