Java Reference
In-Depth Information
class Brick {
public static final
int HEIGHT = 1 0 ;
public static final
int WIDTH = 3 0 ;
public static final
int BRICK H GAP = 2 ;
public static final
int BRICK V GAP = 2 ;
private int x, y;
private Color
color ;
public Brick( int row ,
int col , Color color)
{
this . color = color ;
x=BRICKH GAP + row
(BRICK H GAP + B r i c k . WIDTH) ;
y=BRICKV GAP + c o l
(BRICK V GAP + B r i c k . HEIGHT) ;
}
public void draw(Graphics2D g2)
{
g2 . setPaint ( color ) ;
Rectangle2D r = new Rectangle2D .Double(x, y, WIDTH, HEIGHT) ;
g2. fill (r);
}
}
The constants BRICK H GAP and BRICK V GAP store the horizontal and vertical gap be-
tween the bricks in pixels. The constructor sets the color and computes the top left corner
of the brick. The draw method simply displays the brick, where the top left corner of the
brick and the brick's color are assigned during the construction of the brick.
In addition to ellipses and rectangles, one can display points and lines in Java. A point
in Java is created using the following syntax.
Point2D p = new Point2D. Double(x ,y) ;
The coordinates (x,y) are relative to the top left corner of the panel that contains the
point. Similarly, one can create a line in Java as follows.
Line2D l = new Line2D . Double (x1 , y1 , x2 , y2) ;
Note that (x1,y1) is the starting coordinate of the line and (x2,y2) is the ending
coordinate. This differs from the way that rectangles are ellipses are created. For rectangles
and ellipses, the width and length of the rectangle (or surrounding rectangle) are specified
as the last two parameters.
When drawing a line, one specifies the starting and ending coordinates of the line.
Alternatively, when drawing a rectangle or ellipse, one needs to specify the coordinates
of the top left corner and the width and height of the rectangle (or surrounding
rectangle).
Let us next examine the Player class. It will initially display three player pictures, which
symbolizes that the player initially has three lives. Every time the player loses a life, the
number of pictures will be decremented by one.
class Player {
public static int INITIAL NUM LIVES = 3 ;
public static int IMAGE DISTANCE = 4 0 ;
public static int IMAGE Y = 450;
private int numLives ;

Search WWH ::

Custom Search