Java Reference
In-Depth Information
method can check if the square is an X or an O , while the placeCharacter method changes
the value of the square. Note that it is impossible that a square is both an X and an O at the
same time. Since the variables isX and isO are private , we can guarantee that at no point
both of them are set. The clear method simply resets the value of the rectangle, while the
hasValue method returns true if the square is an X or an O , that is, it has a value.
Note that the Square class inherits from the Rectangle2D.Double class. Therefore, the
Square class will have inside it a rectangular object (as a super object) and we can call
methods, such as getX , getWidth and so on, to retrieve the parameters of the rectangle.
As expected, the constructor of the Square class starts by calling the constructor of the
Rectangle2D.Double class. This sets the top left corner and the width and height of the
rectangle.
Lastly, let us examine the draw method. The paintbrush (an object of type
Graphics2D ) and the possible images to be displayed are passed as parameters. The call
g2.draw(super.getBounds2D()) draws the surrounding rectangle. Next, the drawImage
method is used to display the character X or the character O . Note that the drawImage
method expects the coordinates of the rectangle as integers and therefore we need to cast
the coordinates of our rectangle to integers. Note as well that we have added one to the
second and third parameters in order for the image to not intersect the border. The fourth
and fifth parameters are the size of the image that will be displayed (can be different from
the size of the original image). In our case, we calculate the dimensions as the size of the
rectangle minus two in order to fit the image inside the surrounding rectangular frame.
Next, let us start examining the main class: TicTacToe . We will only override the init
method from the JApplet class in it.
import java .awt . ;
import java . net . ;
import java . util . ;
import javax . imageio . ;
import javax . swing . ;
public class TicTacToe extends JApplet {
private ArrayList < Square > squares = new ArrayList <> () ;
private Image xImage , oImage ;
public void initBoard() {
squares = new ArrayList
<>
() ;
Dimension d = getSize () ;
double dx = d.getWidth() / 3.0;
double dy = d . getHeight () / 3 . 0 ;
for ( int x=0;x
{
for ( int y=0;y < 3 ; y++)
<
3 ; x++)
{
squares .add( new Square(x
dx , y
dy , dx , dy) ) ;
}
repaint () ;
}
public void init()
{
try {
xImage = ImageIO. read ( new URL(getCodeBase () , "images/x.jpg" ));
oImage = ImageIO. read( new URL(getCodeBase () , "images/o.jpg" ));
} catch (Exception exception) {
initBoard() ;
 
Search WWH ::




Custom Search