Drawing Rectangles

Drawing rectangles is simple. Start with a Graphics object g and call its drawRect() method:

public void drawRect(int x, int y, int width, int height)

As the variable names suggest, the first int is the left hand side of the rectangle, the second is the top of the rectangle, the third is the width and the fourth is the height. This is in contrast to some APIs where the four sides of the rectangle are given.

This uses drawRect() to draw a rectangle around the sides of an applet.

import java.applet.*;    
import java.awt.*; 

public class RectangleApplet extends Applet {

  public void paint(Graphics g) {

    g.drawRect(0, 0, this.getSize().width - 1, this.getSize().height - 1);


Remember that getSize().width is the width of the applet and getSize().height is its height.

Why was the rectangle drawn only to getSize().height-1 and getSize().width-1?

Remember that the upper left hand corner of the applet starts at (0, 0), not at (1, 1). This means that a 100 by 200 pixel applet includes the points with x coordinates between 0 and 99, not between 0 and 100. Similarly the y coordinates are between 0 and 199 inclusive, not 0 and 200.

There is no separate drawSquare() method. A square is just a rectangle with equal length sides, so to draw a square call drawRect() and pass the same number for both the height and width arguments.

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
Last Modified June 15, 1998