The Histogram class defines an applet for drawing histograms in a Web page. The idea is to have the user enter data in a textarea and then submit that data to the Histogram applet. The applet code will then parse the data and display the corresponding histogram. For example, the following screenshot shows a histogram of grades received by a student:
An HTML document that would produce this page is listed below:
Copy the source for the Histogram class into a file named Histogram.java and compile it into byte code. Then create the Web page to serve as an interface for this applet.
To create and compile an applet using Visual J++, perform the following steps:
Cut-and-paste the HTML text above into your Histogram.html document and test its behavior.
You might note that if the user clicks on the button without entering any data in the text area, a Java null-pointer exception is raised. Modify the Histogram.java code so that it catches when the parameter is an empty string. In that special case, the applet window should be cleared. Then, recompile and test your applet in the page.
Useful hints: Currently, the code in drawHistogram traverses the data and finds the largest value. You will need to similarly traverse the data to find the longest label (using the string method length()). Once you know the longest label, you can multiply by the approximate number of pixels per character to determine the starting point for histogram bars. Similarly, you must determine the number of digits in the largest bar value and multiply by the number of pixels per character to determine the rightmost limit for histogram bars. In order to determine the number of digits in an integer value, a handy trick is to first convert the int to a string by concatenating it with the empty string "", then use the string method length() (e.g., numDigits = (""+number).length(); ).
When you are testing your code, be aware of the fact that browsers do not always reload applets when a page is reloaded. Holding down the Ctrl key when you click on the Refresh button will usually reload the applet. However, there are times when you must exit the browser completely (close all windows) then restart the browser in order to load changes.