Paint the chess board
First of all we have to define the colors for the dark and bright fields in the class Board:
//Somre colors
Color dunkel = new Color (0x803636);
Color hell = new Color (0xDEDF93);We paint the board with the method
paintField (int index). The methodpaint ()callspaintField ()for each field of the board. Let's have a look at the methodpaint (:
public void paint (Graphics g) {
for ( int i = 21; i < 99; i++) {
paintPiece (i);
if ( i%10 == 8)
i += 2;
}
}We don't want to paint the border, so the loop jumps over all fields of the border. With the modulodivision we get to know if we reached the last line of the regular board. If yes then the loop jumps over the fields of the border.
Now let's look at the method
paintField ():
public void paintField (int index) {
//load graphic reference
Graphics g = getGraphics ();
//look for x and y
int x = (index - 21) % 10;
int y = (index - 21) / 10;
//paint ground field
if ( (x*11 + y) % 2 == 0)
g.setColor( hell );
else
g.setColor( dunkel );
g.fillRect ( x * 40, y * 40, 40, 40);
}In this method we first calculate the X and Y coordinates with the index parameter. The border has no effect of the index. Then the method calculates if the ground field is dark or bright. Then we paint the field with the
fillRect ()Method.Show applet step 2
Source code of step 2