Coloring cells in a Board object

 

Cells in a Board object may take on a color other than black.  Java provides a class that allows us to use common colors and define arbitrary colors called Color.  Color requires an import statement as follows:

 

            import java.awt.Color;

 

Common colors such as green and red can be referred to using the Color constants Color.green and Color.red, respectively.  Java also allows us to create arbitrary colors (over 16 million of them) as Color objects, but for now we’ll only consider the predefined colors.  To color individual cells, we will use the method fillCell, which takes three parameters: the x and y coordinates as integer values and the color constant or object.  Let’s consider this code segment, which creates a 10 by 10 board and colors a few cells (don’t forget the import statement):

 

Board grid = new Board(10, 10);

grid.fillCell(1, 2, Color.green);

grid.fillCell(3, 2, Color.blue);

grid.fillCell(8, 7, Color.red);

grid.fillCell(6, 8, Color.white);

grid.fillCell(1, 8, Color.pink);

grid.fillCell(5, 5, Color.magenta);

grid.fillCell(8, 0, Color.cyan);

 

The resulting Board object will look like the figure to

the left.

 

 

 

 

Instead of filling cells individually, it’s possible to fill a rectangular block of cells with the same color using the fillCells method, which requires 5 parameters instead of three: The x and y coordinates of the top left-hand corner, the x and y coordinates of the bottom right-hand corner, and the color object.  The method will fill all the cells within the rectangle defined by the coordinates with the color specified in the last parameter.  Here’s is an example and its output (above):

 

Board b = new Board(8, 5);

b.fillCells(0, 0, 3, 3, Color.green);

b.fillCells(6, 2, 7, 4, Color.pink);

 

Some methods, such as clear, which removes the attributes of all the cells in the board, take no parameters.  An invocation of such a method using b as the object reference would be:

 

                        b.clear();  // this will clear the board