Java Reference
In-Depth Information
}
public
Color getRandomColor ()
{
Color color =
new
Color ((
int
)
(Math . random ( )
256) ,
∗
(
int
)
(Math . random ( )
256) , (
int
)
(Math . random ( )
256)) ;
∗
∗
if
(getBackground() . equals ( color ))
{
return
Color .RED;
return
color ;
}
public void
showMessage( String s , Graphics2D g2)
{
Font myFont =
new
Font(
"SansSerif"
, Font .BOLD+Font . ITALIC,40) ;
g2. setFont(myFont) ;
g2 . setColor (Color .RED) ;
Rectangle2D textBox = myFont. getStringBounds(s ,
g2 . getFontRenderContext () ) ;
g2. drawString(s , (
int
) (getWidth()/2
−
textBox . getWidth() / 2) ,
(
int
) (getHeight () / 2
−
textBox . getHeight ())) ;
}
public void
paintComponent(Graphics g)
{
super
. paintComponent(g) ;
Graphics2D g2 = (Graphics2D) g ;
if
(bricks.size() == 0)
{
showMessage(
"YOU WIN!"
,g2);
}
else if
(!player . isAlive())
{
showMessage(
"GAME OVER!"
,g2);
}
else
{
ball .draw(g2);
paddle .draw(g2) ;
for
(Brick brick : bricks)
{
brick .draw(g2) ;
}
}
player .draw(g2) ;
}
}
The
BreakoutPanel
class creates the ball, paddle, and bricks. In addition, an object of
Player
class is created. The
Player
class displays icons corresponding to the number of
lives that the player has.
Let us next carefully examine the
paintComponent
method, which is usually the heart
of the panel class. Since this method can be executed multiple times (i.e., every time the
window needs to be repainted), no variable initialization should occur in the method. The
method simply displays the information that is already stored in the instance variables of
the
BreakoutPanel
class. The method takes as input an object of type
Graphics
.This
object is the brush that is needed to paint. Without a handle to this brush, we cannot
display anything in the panel. The first line of the method is
super.paintComponent(g)
.
This line calls the
paintComponent
method of the superclass of the
BreakoutPanel
class,
that is, the
paintComponent
method for the
JPanel
class. The latter method simply clears
the panel (a.k.a. the drawing canvas) so that the new drawings are not displayed on top
of the old drawings. Next, the line
Graphics2D g2 = (Graphics2D) g
converts our brush