Graphic Java

The student has probably observed that there are certain tasks that are repetitive in nature. Java, like all other programming languages, has constructs to deal with repetitive tasks. This activity will deal with for loops. Here's an example:

  for(int x=0; x < 10; x++){
    g.drawString(""+(x+1), 10, 20+x*20);
  }
This example prints out the numbers one through ten. Here's how it works:
  1. int x = 0 This is the initial value of the variable x.
  2. x < 10 This is the ending value of the variable x.
  3. x++ This means that x will be increased by one every time through the loop
  4. { } Whatever is between the curly braces is the action that is taken on every iteration of the loop. The curly braces are optional if the action is only one line long.

Before continuing on, the student should test the for loop shown above by placing it in the paint method.
EXAMPLE: The student will create an applet like the one shown here. This activity provides the student with practice using for loops.
x

ASSIGNMENT:
The student may need some assistance on this activity. Here are the two major steps:

Step One: Create a method to draw a row of filled rectangles:

  public void rowOfRects(Graphics g, int y){
    for(int x = 10; x < 190; x+=15){
      g.fillRect(x,y,10,10);
    }
  }

Step Two: From the paint method call the rowOfRects method for each row to be drawn:
  for(int y=10; y < 190; y+=15){
    rowOfRects(g, y);
  }