Sams Teach Yourself C in 21 Days

(singke) #1
More Java Techniques 753

BD6


Lines 12 to 15 are the mainmethod that is executed when the program is run. Code here
is quite simple, because most of the work of the program is done elsewhere. Line 13 cre-
ates an instance of the program, which causes the constructor in lines 6 to 11 to be exe-
cuted. Line 14 makes the program visible on the screen.
ThedrawShapesmethod in lines 16 to 30 does the job of creating the shapes. Lines 17 to
19 create three different shapes and assign them to elements 0, 1, and 2 of the shapes[]
array that was declared earlier. Line 21 creates a GeneralPathobject, which is used to
combine several individual drawing elements into a single shape. In this statement, a line
is added as the first element of the path. Then lines 23 to 28 add three more lines to the
path, and line 29 assigns the resulting drawing object to element 3 of the shapes[]array.
Note that this code only creates the shapes but does not display them.
Lines 22 to 38 define the class MyCanvas, which is a subclass of the AWT class Canvas.
As the name implies, this class provides a surface on which you can draw. An instance of
MyCanvaswas placed in the program’s window on line 10, so it is all ready for use. Lines
33 to 37 define the paintmethod (actually you are replacing the Canvasclass’s own
paintmethod). This method is automatically called whenever the window needs
refreshing, such as when the program first starts, or if it is restored after being mini-
mized. The code in this method creates an instance of the Graphics2Dclass and then
loops through the shapes[]array using the drawmethod to draw each shape.

FIGUREB6.2
Graphics output cre-
ated by the program in
Listing B6.4.

41 448201x-Bonus6 8/13/02 11:23 AM Page 753

Free download pdf