Java Reference
In-Depth Information
32
33
// x is the start position for the first bar in the histogram
34
int
x =
30
;
35
36
// Draw a horizontal base line
37 g.drawLine(
10
, height -
45
, width -
10
, height -
45
);
38
for
(
int
i =
0
; i < count.length; i++) {
39
// Find the bar height
40
int
barHeight =
41
(
int
)(((
double
)count[i] / (
double
)maxCount) * (height -
55
));
42
43
// Display a bar (i.e., rectangle)
44 g.drawRect(x, height -
45
- barHeight, individualWidth,
45 barHeight);
46
47
// Display a letter under the base line
48 g.drawString((
char
)(
65
+ i) +
""
, x, height -
30
);
49
50
// Move x for displaying the next character
51 x += interval;
52 }
53 }
54
55 @Override
56
public
Dimension getPreferredSize() {
preferredSize
57
return new
Dimension(
300
,
300
);
58 }
59 }
The program contains two classes:
MultipleWindowsDemo
and
Histogram
. Their relation-
ship is shown in Figure 17.16.
javax.swing.JPanel
javax.swing.JFrame
1
1
Histogram
MultipleWindowsDemo
-count: int[]
+showHistogram(count: int[]): void
#paintComponent(g: Graphics): void
-jta: JTextArea
-histogram: Histogram
-jbtShowHistogram: JButton
-countLetters(): int[]
+main(args: String[]): void
F
IGURE
17.16
MultipleWindowsDemo
uses
Histogram
to display a histogram of the
occurrences of the letters in a text area in the frame.
MultipleWindowsDemo
is a frame that holds a text area in a scroll pane and a button.
Histogram
is a subclass of
JPanel
that displays a histogram for the occurrences of letters in
the text area.
In Listing 17.8, MultipleWindowsDemo.java, when the user clicks the
Show Histogram
button, the handler counts the occurrences of letters in the text area (line 29). Letters are
counted regardless of their case. Nonletter characters are not counted. The count is stored in
an
int
array of
26
elements (line 48). The first element in the array stores the count for the
letter
a
or
A
, and the last element stores the count for the letter
z
or
Z
(lines 57-63). The
count
array is passed to the histogram for display (line 32).
The
MultipleWindowsDemo
class contains a
main
method. The
main
method creates an
instance of
MultipleWindowsDemo
and displays the frame (lines 69-74). The