Java Reference
In-Depth Information
TABLE 9 . 1 :
Font masks.
Mask Result
Font.BOLD
bold font
Font.ITALIC
italic font
Font.PLAIN
plain font
Font.BOLD+Font.Italic
bold and italic font
to a two-dimensional brush. In this topic, we will only cover how to draw different shapes
(e.g., rectangles, circles, and ellipses) using a brush of type
Graphics2D
.
The variable
bricks
stores an
ArrayList
of bricks. Every time the ball hits a brick,
we will remove the brick that is hit from the
ArrayList
. When the
ArrayList
becomes
empty, we need to print “You Win”. This is done by the
showMessage
method. Note that
the brush is passed as a parameter to the method. The reason is that there must be access
to the brush before anything can be displayed in the panel. If the player is no longer alive,
then we will display the message “GAME OVER”. Otherwise, if the game continues, we
will display the ball, the paddle, and the bricks. Since there are multiple bricks, we need a
for
statement to iterate over all the bricks. Finally, we will display the number of lives on
the screen. Note that all the drawing methods take as input the brush. It is needed in order
to do the painting.
Next, let us examine the
showMessage
method. Before we can display text inside the
panel, we need to set the font for the text. Since everything in Java is object oriented, we
will first create an object of type
Font
. The constructor of the
Font
class takes as input
three parameters: the name of the font, the mask of the font (used to determine whether
the text should be bold, italic, or both), and the point size of the font. A problem arises
when the font that we want to use is not supported by the operating system. There are two
ways to deal with this problem. One way is to use one of the predefined five fonts.
SansSerif
Serif
Monospaced
Dialog
DialogInput
Java guarantees that these fonts can be used under any configuration of any operating
system. If the operating system does not support one of the fonts, then Java will use
the closest available font instead. The second option is to check the available fonts before
committing to a font. The following expression will return an array of strings that contains
all the fonts that are currently installed.
String [ ] fontNames =GraphicsEnvironment . getLocalGraphicsEnvironment () .
getAvailableFontFamilyNames () ;
The first parameter of the constructor of the
Font
class is the name of the font. The
second parameter is a combination of font masks. Table 9.1 shows popular choices. Note
that
BOLD
,
ITALIC
,and
PLAIN
are defined as constants (i.e.,
static final
variables) in
the
Font
class. The constant
PLAIN
has all bits set to 0 (0000 0000 in binary notation).
All other constants have exactly one bit set. For example,
BOLD
can be defined as 0000
0001 in binary notation and
ITALIC
can be defined as 0000 0010 in binary notation. Then
the expression BOLD+ITALIC will be equal to 0000 0011, that is, the bits for both bold