CS 201 - Computer Science I - Spring 2003
Lab 1 - Drawing in Java


Loyola College > Department of Computer Science > CS 201 > Labs > Lab 1

Due

Wednesday, January 29 at 11:59pm. Labs submitted one day late will be assessed a 20% penalty. Labs will not be accepted more than one day late.

Objectives

Reading

Decker and Hirshfield, sections 2.1 through 2.3

Introduction

Drawing in Java applets can done in the paint method by using the methods of the Graphics object that is passed to paint. Graphics has methods drawRect, drawOval, and drawString to put outlines of shapes or text on the screen. fillRect and fillOval can be used to draw filled shapes.

The rectangle and oval drawing methods each take four parameters: the x-coordinate of the upper left corner, the y-coordinate of the upper left coordinate, the width, and the height (the "corner" of an oval is the corner of the rectangle that encloses it). All of the measurements are done in pixels. A pixel is the smallest dot that can be drawn on a computer screen. The x-coordinate of a point is given by how many pixels to the right of the left egde of the window that point is. The y-coordinate is given by how many pixels below the top edge the point is (note that this is the opposite of how the y-axis works in math). So (0, 0) is the upper left corner of the window and for jGRASP's default 400x400 window, (399, 399) is the lower right corner.

drawString's parameters are, in order, the string to draw, the x-coordinate of the left of the string, and the y-coordinate of the baseline of the string (the bottom of letters without descenders). The string parameter should be enclosed in double quotes (") if you wish to display the same string each time the applet is executed.

Different parts of a picture can be drawn in different color by using the setColor method in Graphics. setColor takes as its parameter a Color, which can be any one of several predefined colors Color.red, Color.blue, Color.green, etc. (other custom-blended colors are also possible). After setColor has been called, any object drawn with the other methods is drawn in the color passed to setColor (by default, at the beginning of paint everything is drawn in black).

We could design an applet that displays a small red circle with a caption below it in the middle of its window by giving it the following paint method.

public void paint(Graphics g)
{
  g.drawString("Circle", 182, 216);
  g.setColor(Color.red);
  g.drawOval(195, 195, 10, 10);
}

Assignment

Write an applet that displays a picture like the one below. Call your applet class TruckDrawing.

Suggestions

Make a sketch of the truck on paper and try to figure out what all the coordinates will be before writing the code.

Submissions

Submit the source code (.java file) for your TruckDrawing class.