Java Reference
In-Depth Information
13
14
// constructor, creates a panel with random shapes
15
public
DrawPanel()
16
{
17
setBackground(
Color.WHITE
);
18
19
lines =
new
MyLine[
5
+ randomNumbers.nextInt(
5
)];
20
21
// create lines
22
for
(
int
count =
0
; count < lines.length; count++)
23
{
24
// generate random coordinates
25
int
x1 = randomNumbers.nextInt(
300
);
26
int
y1 = randomNumbers.nextInt(
300
);
27
int
x2 = randomNumbers.nextInt(
300
);
28
int
y2 = randomNumbers.nextInt(
300
);
29
30
// generate a random color
31
Color color =
new
Color(randomNumbers.nextInt(
256
),
32
randomNumbers.nextInt(
256
), randomNumbers.nextInt(
256
));
33
34
// add the line to the list of lines to be displayed
35
lines[count] =
new
MyLine(x1, y1, x2, y2, color);
36
}
37
}
38
39
// for each shape array, draw the individual shapes
40
public
void
paintComponent(Graphics g)
41
{
42
super
.paintComponent(g);
43
44
// draw the lines
45
for
(MyLine line : lines)
46
line.draw(g);
47
}
48
}
// end class DrawPanel
Fig. 8.18
|
Program that uses class
MyLine
to draw random lines. (Part 2 of 2.)
Class
TestDraw
Class
TestDraw
in Fig. 8.19 sets up a new window to display our drawing. Since we're set-
ting the coordinates for the lines only once in the constructor, the drawing does not
change if
paintComponent
is called to refresh the drawing on the screen.
1
// Fig. 8.19: TestDraw.java
2
// Creating a JFrame to display a DrawPanel.
3
import
javax.swing.JFrame;
4
5
public
class
TestDraw
6
{
Fig. 8.19
|
Creating a
JFrame
to display a
DrawPanel
. (Part 1 of 2.)