Java Reference
In-Depth Information
51 String text = jta.getText();
52
53
// Count occurrences of each letter (case insensitive)
54
for
(
int
i =
0
; i < text.length(); i++) {
55
char
character = text.charAt(i);
56
57
if
(character >=
'A'
&& character <=
'Z'
) {
58 count[character -
'A'
]++;
59 }
60
else if
(character >=
'a'
&& character <=
'z'
) {
61 count[character -
'a'
]++;
62 }
63 }
64
65
return
count;
// Return the count array
66 }
67
68
public static void
main(String[] args) {
69 MultipleWindowsDemo frame =
new
MultipleWindowsDemo();
70 frame.setLocationRelativeTo(
null
);
// Center the frame
71 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
72 frame.setTitle(
"MultipleWindowsDemo"
);
73 frame.pack();
74 frame.setVisible(
true
);
75 }
76 }
create main frame
L
ISTING
17.9
Histogram.java
1
import
javax.swing.*;
2
import
java.awt.*;
3
4
public class
Histogram
extends
JPanel
{
5
// Count the occurrences of 26 letters
6
private int
[] count;
7
8
/** Set the count and display histogram */
9
public void
showHistogram(
int
[] count) {
10
this
.count = count;
11 repaint();
12 }
13
14 @Override
/** Paint the histogram */
15
protected void
paintComponent(Graphics g) {
paint histogram
16
if
(count ==
null
)
return
;
// No display if count is null
17
18
super
.paintComponent(g);
19
20
// Find the panel size and bar width and interval dynamically
21
int
width = getWidth();
22
int
height = getHeight();
23
int
interval = (width -
40
) / count.length;
24
int
individualWidth = (
int
)(((width -
40
) /
24
) *
0
.
60
);
25
26
// Find the maximum count. The maximum count has the highest bar
27
int
maxCount =
0
;
28
for
(
int
i =
0
; i < count.length; i++) {
29
if
(maxCount < count[i])
30 maxCount = count[i];
31 }