Java Reference
In-Depth Information
WINDOW TITLE
(0,0)
(x,y)
FIGURE 9.3: Coordinates of a ball.
bricks will change every time the panel is resized. This is, certainly, undesirable behavior of
the program.
Next, let us consider the Ball class and how it displays the game ball.
class Ball {
public static final
int SIZE = 10;
public static final
int START X = 200;
public static final
int START Y = 400;
private Color color ;
private int x, y;
public Ball (Color color )
{
this . color = color ;
x=STARTX;
y=STARTY;
}
public void draw(Graphics2D g2)
{
g2 . setPaint ( color ) ;
Ellipse2D e = new Ellipse2D.Double(x, y, SIZE, SIZE) ;
g2 . f i l l (e) ;
}
}
A ball is characterized by its location in the panel and its color. Note that creating
a Ball class allows us to easily extend the game and add multiple balls if needed. The
x and y coordinates of the ball correspond to the top left corner of the virtual rectangle
that surrounds the ball. The coordinates are relative to the top left corner of the panel; see
Figure 9.3.
The constructor of the Ball class sets the color and starting (x,y) coordinates of the
ball. The draw method displays the ball. In order to be able to draw inside a panel, an
access to the 2-D drawing brush is needed. It is passed as a parameter to the method. The
method first sets the color of the brush. All consecutive drawing operations will use this
color until the color of the brush is changed. Next, an ellipse object is created and drawn.
An ellipse is created because Java does not have a class for a circle (an ellipse is a special
case of a circle).
Let us now carefully examine the Ellipse2D.Double class. It inherits from the
Ellipse2D class. It is unusual to have a class name that contains a dot in the middle.
 
Search WWH ::




Custom Search