Java Reference
In-Depth Information
9.3 Panels and Drawing
Our program, as written so far, will display an empty window. Our next task is to display
the bricks, ball, paddle, and player icons inside the window (we will display a player icon
for each life remaining). Java does not allow us to directly draw inside a window. Instead, it
requires that first a canvas (called a panel) be created. The content of the panel may have
to be repainted many times during the execution of a program. For example, every time a
window is restored after being minimized and every time a window is resized, its content is
repainted.
Java calls the
paintComponent
method of the panel to do the painting. This
method is unique because it cannot be directly called by your Java program. Al-
ternatively, you should call the
repaint
method in order to force the refreshing of the
content of the panel. The
repaint
method forces the
paintComponent
method to be
called sometime in the future.
The behavior of the
paintComponent
method is not trivial and is tricky to understand
by novice programmers. Here is an important principle to remember.
The programmer has no control of when the
paintComponent
method will be
called. Therefore, it is important that the behavior of the method be consistent
with previous executions of the method. For example, never generate data inside the
method. The method should be used to
only to display the data
,wherethedata
can be created in the constructor of the panel or as the result of events occurring.
If the programmer generates and displays data inside the method, then the behavior
of the application will be strange. For example, the drawing inside the window can
change just because the screen is resized.
We will add to end of the constructor of the
BreakoutFrame
class the following code.
BreakoutPanel panel =
new
BreakoutPanel () ;
add(panel) ;
This creates the panel and adds it to the windows. Let us now examine the code for the
BreakoutPanel
class.
class
BreakoutPanel
extends
JPanel
{
public static final int
NUM BRICK ROWS = 10;
public static final int
NUM BRICK COLUMNS = 30;
private
Ball ball =
new
Ball (Color . red) ;
private
ArrayList
<
Brick
>
bricks =
new
ArrayList
<>
() ;
private
Paddle paddle =
new
Paddle(Color .BLUE) ;
private
Player player =
new
Player () ;
public
BreakoutPanel ()
{
for
(
int
row = 0; row
<
NUM BRICK ROWS ; row++)
{
for
(
int
col = 0; col
<
NUM BRICK COLUMNS ; c o l ++)
{
bricks .add(
new
Brick (row , col , getRandomColor () ) ) ;
}
}