1
Student Name: __________________
Class and Section __________________
Total Points (20 pts) __________________
Due: December 7, 2009 before the class
Final Project: Histogram
CSCI 1302 Advanced Programming Principles
Armstrong Atlantic State University
Problem Description:
Develop a program that displays a histogram to show the occurrences of each
letter in a text area. The histogram should show the occurrences of each letter in a
text file, as shown in the following figure. Assume that the letters are not case
sensitive.
Submit the following items:
1. Compile and Submit to LiveLab (you must submit the program regardless whether it
complete or incomplete, correct or incorrect)
2. Fill in self-evaluation:
1. Can your program create the UI? _______________
2. Can your program handle action event from the text field? _______________
3. Can your program read text from the file?_______________
_______________
2
3
Solution Code:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
setLayout(new BorderLayout());
add(p, BorderLayout.SOUTH);
add(display, BorderLayout.CENTER);
jtf.addActionListener(new Listener());
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Reset counts
for (int i = 0; i < 26; i++) {
counts[i] = 0;
}
}
}
}
display.showHistogram(counts);
}
catch (FileNotFoundException ex) {
System.out.println(“File not found: ” + jtf.getText().trim());
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
4
import javax.swing.*;
import java.awt.*;
public class Histogram extends JPanel {
// Count the occurrence of 26 letters
private int[] count;
/** Set the count and display histogram */
public void showHistogram(int[] count) {
this.count = count;
repaint();
}
/** Paint the histogram */
protected void paintComponent(Graphics g) {
if (count == null) return; // No display if count is null
super.paintComponent(g);
}
// x is the start position for the first bar in the histogram
int x = 30;
// Draw a horizontal base line
g.drawLine(10, height – 45, width – 10, height – 45);
for (int i = 0; i < count.length; i++) {
// Find the bar height
int barHeight =
(int)(((double)count[i] / (double)maxCount) * (height – 55));
// Display a bar (i.e. rectangle)
g.drawRect(x, height 45 – barHeight, individualWidth,
barHeight);