|
This latest example also demonstrates one other thing. Until now you may have thought that we were passing two points to the drawRect and fillRect methods and drawing the rectangle that joins them. This is how rectangles are implemented in QuickDraw on the Mac for example. However if that was the case the preceding rectangle would have been drawn between (100, 100) and (100, 100), a fairly small rectangle. Since that isn't the case our association of the last two variables with and must be correct. The extremely astute reader may object at this point. Until now we've only drawn squares. Although the last two variables passed to drawRect and fillRect must be the and the how do we know which is which? The simplest way to tell is to write a test program that draws a non-square rectangle. Let's try that now: //Draw a rectangle import java.applet.Applet; import java.awt.*; public class Mondrian4 extends Applet { int Rect, Rect, RectTop, RectLeft, Applet, Applet; public void init() { Dimension d = size(); Applet = d.; Applet = d.; Rect = Applet/3; Rect = (Applet*2)/3; RectTop = (Applet - Rect)/2; RectLeft= (Applet - Rect)/2; repaint(); } public void paint(Graphics g) { g.drawRect(0, 0, Applet-1, Applet-1); g.fillRect(RectLeft, RectTop, Rect-1, Rect-1); } } So you see that the third argument is indeed the and the fourth is the . Now that we've learned how to draw rectangles, both filled and unfilled, let's make life a little more exciting by randomly selecting the position and size of the rectangle. To do this we'll need the Math.random() method from java.lang.Math. This method returns a double between 0.0 and 1.0 so we'll need to multiply the result by the applet's and to get a reasonably sized rectangle that fits into our applet space. To do this we'll create the following Randomize method: private int Randomize( int range ) { double rawResult; rawResult = Math.random(); return (int) (rawResult * range); }
|
Bhopal news
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100