Java Reference
In-Depth Information
The program that produces
Figure 9
is composed of three classes.
Figure 10
Using Graph Paper to Find Shape Coordinates
113
114
ȗ The
Car
class is responsible for drawing a single car. Two objects of this class
are constructed, one for each car.
ȗ The
CarComponent
class displays the drawing.
ȗ The
CarViewer
class shows a frame that contains a
CarComponent
.
Let us look more closely at the
CarComponent
class. The
paintComponent
method draws two cars. We place one car in the top-left corner of the window, and
the other car in the bottom right. To compute the bottom right position, we call the
getWidth
and
getHeight
methods of the
JComponent
class. These methods
return the dimensions of the component. We subtract the dimensions of the car:
Car car1 = new Car(0, 0);
int x = getWidth() - 60;
int y = getHeight() - 30;
Car car2 = new Car(x, y);