Sams Teach Yourself C in 21 Days

(singke) #1
9: drawShapes();
10: add(“Center”, new MyCanvas());
11: }
12: public static void main(String args[]) {
13: DrawingTest app = new DrawingTest(“Drawing test”);
14: app.show();
15: }
16: void drawShapes () {
17: shapes[0] = new Rectangle2D.Double(12.0,12.0, 98.0, 120.0);
18: shapes[1] = new Ellipse2D.Double(150.0, 150.0,90.0,30.0);
19: shapes[2] = new RoundRectangle2D.Double(200.0, 25,
20: 235.0, 250.0, 50.0, 100.0);
21: GeneralPath path = new GeneralPath(new Line2D.Double(100.0,
22: 350.0, 150.0, 300.0));
23: path.append(new Line2D.Double(150.0, 300.0,
24: 200.0, 350.0), true);
25: path.append(new Line2D.Double(200.0, 350.0,
26: 250.0, 300.0), true);
27: path.append(new Line2D.Double(250.0, 300.0,
28: 300.0, 350.0), true);
29: shapes[3] = path;
30: }
31:
32: class MyCanvas extends Canvas {
33: public void paint(Graphics graphics) {
34: Graphics2D gr = (Graphics2D) graphics;
35: for (int i=0; i<4; i++)
36: gr.draw(shapes[i]);
37: }
38: }
39: }

See Figure B6.2.
Lines 1 and 2 import the required AWT classes. Line 4 defines the program as a
subclass of Frame, required to display a screen window. Line 5 declares an array
of type Shapethat is an AWT class for drawing shapes.
Lines 6 to 11 make up the class constructor and are executed when the program is instan-
tiated. Line 7 uses the superkeyword to pass the program title to the Framesuperclass.
Line 8 sets the window size to be 500 pixels wide and 400 pixels high. Line 9 calls the
drawShapesmethod (defined later) to create the shapes, and line 10 creates an instance
ofMyCanvas(also defined later) and adds it, centered, to the window.

752 Bonus Day 6

LISTINGB6.4 continued

OUTPUT

ANALYSIS

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

Free download pdf