A Rectangle Example

The example in this section illustrates how to divide areas of an application’s client area into sub-rectangles, and how to work within these regions.

When the application starts, it divides the main form’s client area into 16 by 16 sub-regions, and displays every shade of a given color within those rectangular regions. To modify the number of rectangles displayed across and down the display, you use the Dimensions menu item to display a dialog box in which you specify the new number of rectangles you’d like to see displayed.

The method that divides the screen into Rectangle objects is given in the following example. This method, getRects, takes three parameters: a rectangle that specifies the area to be divided, and two integers, which identify the number of cells to draw across and down, respectively. The method returns an array of rectangles that contain the appropriate coordinates:

private Rectangle[] getRects(Rectangle rcClient, int nDown, int nAcross){

   int deltaX, deltaY;   // The height and width of each cell.
   int x, y;
   int i;

   Rectangle rgRects[] = new Rectangle[nDown * nAcross];

   // Determine the height and width of each Rectangle.

   deltaX = (rcClient.getRight() – rcClient.x) / nAcross;
   deltaY = (rcClient.getBottom() – rcClient.y) / nDown;

   // Create and initialize the Rectangle array.

   for(y = rcClient.y, i = 0; y < rcClient.getBottom(); y += deltaY){
      for(x = rcClient.x; x < (rcClient.getRight() – nAcross) &&
            i < (nAcross * nDown); x += deltaX, i++){

         rgRects[i] = new Rectangle(x, y, deltaX, deltaY);
      }
   }

   // Return the initialized array.

   return rgRects;
}

When the application starts, its Form class constructor initializes two class-level integers, nAcross and nDown, to 16, and calls the getRects method previously listed:

public Form1(){

   initForm();
   nAcross = 16;
   nDown = 16;

   // Initialize class-level array.

   rgRects = getRects(this.getClientRect(), nAcross, nDown);
}

After the class constructor returns, the class’ paint event handler is automatically called. This event handler loops through the class-level rgRects array, uses the Graphics object’s setBrush method to set a new color, and then calls the drawRect method to draw the array’s rectangle:

protected void onPaint(PaintEvent e){
   
   for(int i = 0; i < rgRects.length; i++){
      
      e.graphics.setBrush(new Brush(new Color(0,0,i)));
      e.graphics.drawRect(rgRects[i]);
   }
}

Finally, the Form class’ resize handler simply re-initializes the array and forces a repaint of the form’s client area:

protected void onResize(Event e){

   Rectangle rcClient = this.getClientRect();
   rgRects = getRects(rcClient, nDown, nAcross);
   this.invalidate();
}