The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


A lame Mickey Mouse

Let's say we want to draw a picture of Mickey Mouse. We can use the oval we just drew as the face, and then add ears. Before we do that it is a good idea to break the program up into two methods. main will create the Slate and Graphics objects and then invoke draw, which does the actual drawing.

  public static void main (String[] args) {
    int width = 500;
    int height = 500;

    Slate slate = Slate.makeSlate (width, height);
    Graphics g = Slate.getGraphics (slate);

    g.setColor (Color.black);
    draw (g, 0, 0, width, height);
  }

  public static void draw
               (Graphics g, int x, int y, int width, int height) {
    g.drawOval (x, y, width, height);
    g.drawOval (x, y, width/2, height/2);
    g.drawOval (x+width/2, y, width/2, height/2);
  }

The parameters for draw are the Graphics object and a bounding box. draw invokes drawOval three times, to draw Mickey's face and two ears. The following figure shows the bounding boxes for the ears.

As shown in the figure, the coordinates of the upper-left corner of the bounding box for the left ear are (x, y). The coordinates for the right ear are (x+width/2, y). In both cases, the width and height of the ears are half the width and height of the original bounding box.

Notice that the coordinates of the ear boxes are all relative to the location (x and y) and size (width and height) of the original bounding box. As a result, we can use draw to draw a Mickey Mouse (albeit a lame one) anywhere on the screen in any size. As an exercise, modify the arguments passed to draw so that Mickey is one half the height and width of the screen, and centered.



Last Update: 2011-01-24