Java Reference
In-Depth Information
public
Player ()
{
this
. numLives = INITIAL NUM LIVES ;
}
public void
killPlayer()
{
numLives
−−
;
}
public boolean
isAlive()
{
return
(numLives
>
0) ;
}
{
public void
draw(Graphics2D g2)
try
{
Image image = ImageIO. read (
new
File(
"player.gif"
));
for
(
int
x=0;x
<
numLives ; x++)
{
g2 . drawImage( image , x
IMAGE DISTANCE,
IMAGE Y,
null
);
∗
}
}
catch
(Exception myException)
{}
}
}
The
killPlayer
method reduces the number of lives by one. The
isAlive
method
checks if there are any lives left. The
draw
method draws the specified number of stickmen
on the panel. The image for the stickman is read from a file. The command:
Image image = ImageIO. read (
new
File(
"player.gif"
));
reads an image from the file
player.gif
and associates the image with the object image.
The file
player.gif
must be in the root project directory. Alternatively, a path where
the file is stored can be specified as follows:
c:/pictures/player.gif
. Note that a forward
slash should be used regardless of the operating system. The reason is that a backward slash
has a special meaning in Java. Note that an exception can occur if the specified file does
not exist on the hard disc. Unlike most languages, Java forces us to handle such exceptions.
The
try-catch
block handles the exception. The catch part is empty, which means that we
will do nothing when an exception occurs. The code where the exception can occur is put
in the
try
block. More information about exceptions will be provided in Chapter 13. Note
that the
draw
method cannot throw an exception because it overrides the
draw
method in
the
JPanel
class that does not throw an exception. In other words, the following version of
the
draw
method will not compile.
public void
draw(Graphics2D g2)
throws
Exception
{
Image image = ImageIO. read (
new
File(
"player.gif"
));
for
(
int
x=0;x
<
numLives ; x++)
{
g2 . drawImage( image , x
IMAGE DISTANCE,
IMAGE Y,
null
);
∗
}
}
The above code means that the
draw
method will not handle the exception and it will
simply require the calling method to deal with it. This is a handy way of handling exceptions
when it is possible to implement.
The command:
g2 . drawImage( image , x
IMAGE DISTANCE, IMAGE Y,
null
);
∗
draws the image, where
(x,y)
is the top left corner of the image. The last parameter is an