|
The char type and adding text to cells |
|
In addition to color attributes, each cell can
be associated with a single character.
Java provides the type char to represent
a single character or symbol from virtually all known alphabets or symbol
sets in the world. Initially, well
limit ourselves to the character set on our keyboards, which is easiest to
deal with. A char value in Java is surrounded by single quotes, unlike integer
values. Since digits are part of our
symbol set, a digit that is surrounded by single quotes is treated as a char value (Well find out later on what the difference is between
the expressions 1+1 and 1+1). Here
are some char variable declarations: char ch1 = A; //
ch1 is the variable and A is its value char
ch2 = 3; char
ch3 = @; char
ch4 = ; // yes, a space is a valid
character When you create a Board object, all of its
cells have a character associated with them the space. To change the character content of a cell,
we use the method setChar, which requires
3 parameters: the x and y coordinates, and the character to associate with
the cell (not surprising). Heres a
full program that will print out CSC152, one character per cell, on a 6x1
board colored yellow. import java.awt.Color; public class CSC152Board { public
static void main(String[] args) { Board b
= new Board(6,1); b.fillCells(0, 0, 5, 0, Color.yellow); b.setChar(0, 0, 'C'); b.setChar(1, 0, 'S'); b.setChar(2, 0, 'C'); b.setChar(3, 0, '1'); b.setChar(4, 0, '5'); b.setChar(5, 0, '2'); } }
|