0 1 2
3 4 5
6 7 8
FIGURE 15.3: The index of the squares in the Tic-Tac-Toe game.
addMouseListener( new MyMouseListener () ) ;
Note that we did not define the number of rows and columns in the grid as constants.
The reason is that our code is very specific and it works only for the 3x3 version of the game.
The class has two variables: for the images and for the squares. The init method creates
the board and the images and adds a mouse listener. The code of the initBoard method
is moved into a separate method because it will be called multiple times. For example, we
will need to call the method after every win, lost, or tie. This will allow the user to play
multiple games without having to reload the applet. Note the getCodeBase method.
The getCodeBase method can be called on a JApplet object. It returns the URL
location of applet files.
The method is used to find the code base directory. Note that we set this directory in
the HTML file with the line.
< APPLET c o d e b a s e= "classes" code= "TicTacToe.class" width=350 height
=200 >< /APPLET >
This means that there is a subdirectory classes of the directory that contains the HTML
file. This is the code base directory. The call new URL(getCodeBase(), "images/x.jpg")
specifies the remote location from which the image can be downloaded. URL stands for
uniform resource locator and specifies the Internet location of a resource, such as a file.
In order for this to work, we need to create a subdirectory in the folder classes with
name images and place the two image files there. Note that the getCodeBase method only
applies to Java Applets. Since there is extra security when running a Java applet, we cannot
specify an arbitrary file location. We can only access files from the code base directory and
its subdirectories. Note that the actual file x.jpg is not saved on the client's side. Instead,
it is read from the server and stored in the main memory of the client. The ImageIO.read
method reads the file in the main memory of the client.
The initBoard method creates the nine squares of the game. Examine Figure 15.3 to
see the index of each square. Note that we do not initially know the dimensions of the
applet window because these are set from the HTML file. However, we can use the getSize
method to get the size of the applet window. The applet window is then divided into nine
equal parts. After the board is created, we call the repaint method to repaint the applet.
Next, let us examine the paint method inside the TicTacToe class.