Java Reference
In-Depth Information
3. Implement the
actionPerformed
handler in
MultipleWindowsDemo
, as follows:
a. Create an instance of
Histogram
. Count the letters in the text area and set the count
in the
Histogram
object.
b. Create a new frame and place the
Histogram
object in the center of frame. Display
the frame.
L
ISTING
17.8
MultipleWindowsDemo.java
1
import
java.awt.*;
2
import
java.awt.event.*;
3
import
javax.swing.*;
4
5
public class
MultipleWindowsDemo
extends
JFrame {
6
private
JTextArea jta;
7
private
JButton jbtShowHistogram =
new
JButton(
"Show Histogram"
);
8
9
10
private
Histogram histogram =
new
Histogram();
// Create a new frame to hold the histogram panel
11
12
13
public
MultipleWindowsDemo() {
14
// Store text area in a scroll pane
15 JScrollPane scrollPane =
new
JScrollPane(jta =
new
JTextArea());
16 scrollPane.setPreferredSize(
new
Dimension(
300
,
200
));
17 jta.setWrapStyleWord(
true
);
18 jta.setLineWrap(
true
);
19
20
// Place scroll pane and button in the frame
21 add(scrollPane, BorderLayout.CENTER);
22 add(jbtShowHistogram, BorderLayout.SOUTH);
23
24
private
JFrame histogramFrame =
new
JFrame();
create subframe
create UI
// Register listener
25
26 @Override
/** Handle the button action */
27
jbtShowHistogram.addActionListener(
new
ActionListener() {
public void
actionPerformed(ActionEvent e) {
28
// Count the letters in the text area
29
int
[] count = countLetters();
30
31
// Set the letter count to histogram for display
32 histogram.showHistogram(count);
33
34
// Show the frame
35 histogramFrame.setVisible(
true
);
36 }
37 });
38
39
display subframe
// Add the histogram panel to the frame
40
41
42 histogramFrame.setTitle(
"Histogram"
);
43 }
44
45
histogramFrame.add(histogram);
histogramFrame.pack();
/** Count the letters in the text area */
46
private int
[] countLetters() {
47
// Count for 26 letters
48
int
[] count =
new int
[
26
];
49
50
// Get contents from the text area