Http://www.builderau.com.au/program/java/soa/Creating-pie-charts-with-JSP-is-a-breeze/0,339024620,320273905,00.htm
Creating pie charts with JSP is a breeze
Java Server Pages (JSP) makes it easy to read and summarise data from a database and then display the results in a pie chart. we'll show you what you need to do to tap into this functionality.
Java Server Pages (JSP) offers several simple techniques for reading transactions from a database, summarising data, and Displaying results in a pie chart. let's look at the details of getting these pages out the door.
What do you need?
To get started with the examples in this article, you need JDK 1.2 or higher, a relational database management system, and a JSP web server. I tested these examples on Tomcat, and I usedCom.sun.image.codec.jpegClasses that are distributed with the Sun Java 2 SDK. With this setup intact, we're re ready to focus on the design.
Database Design
Imagine that you work for a fictitious company that sells fresh produce, such as apples, oranges, and grapes. the owners want a pie chart showing the total sales of each product. A pie chart gives the owners a simple summary of their sales and provides a visual tool to quickly establish the products with the greatest turnover.
ListingSummarises the two database tables used in this article. The first table (products) contains the names of all saleable products; the second table (sales) contains individual sales transactions per product.
The Products table has productid and productname fields. The sales table has saleid, productid, and amount. The productid In the sales table provides the relationship between the two tables, linking to the productid in the products table.The salesTable'sAmount field contains the cash values of each sale, which are represented by float values.
The getproducts () method (Listing B) Connects to the database and stores all the product names in an array. I have set the following Database Rules:
- The productid Is the unique, primary key for the product table.
- The productid for the first record will be zero (0 ).
- All subsequent records are autonumbered, so the second record's productid Will be 1, the third record's productid Will be 2, and so on.
These database rules allow the storage of data inProductsArray as follows:
Arr [RS. getint ("productid")] = Rs. getstring ("productname ");
Some database management systems leave it up to the programmer to maintain the integrity of the autonumbering or sequencing system. when designing your database, you'll want to find out how your database management system handles design-time rules such as autonumbering, sequences, and null or default values.
Getting total sales
Most likely, there will be a lot of records in the sales table (since there is one record per sale), so it is necessary to make database access as quick and efficient as possible. we need only the total sales for each product.
The getsales () method (Listing c) Connects to the database and returns an array that contains the total sale figures for each product. as getsales () loops through the sales transaction records, it simply stores the new sales total for each product:
Int Product = Rs. getint ("productid ");
Arr [product] + = Rs. getfloat ("amount ");
The piecolor object
Each product on the pie chart needs to be displayed in a different color. To facilitate this, I have created a piecolor object (Listing d), Which contains an arrayColorObjects:
Color piecolorarray [] = {new color (60,210, 60, 60), new color (, 60 )...}
The piecolor class defines a setnewcolor () method, which increments curpiecolor,The index used to access the piecolorarray [].The method also checks that the array's index does not go out of bounds by setting the value of curpiecolor to zero if it grows too large.
In effect, setnewcolor () Loops through the available colors and starts again with the first color when all of the colors have been used:
Curpiecolor ++;
If (curpiecolor> = piecolorarray. length)
{Curpiecolor = 0 ;}
The renderinghints class and antialiasing
The Java. AWT. renderinghints class defines several fields that are used when displaying graphics2d images, including alpha_interpolation, dithering, and antialiasing. renderinghints helps to determine how the image shocould be displayed and how (or whether) the image shocould be optimised.
For a smooth display, it is important to use antialiasing to create pie charts. antialiasing is the process by which jaged computer-generated lines in an image are smoothed. the antialiasing algorithm selects the color value of a particle pixel and replaces the adjacent pixels with color values that make the original pixel look less jarged.
FigureWhen strates the effects of antialiasing. Note that the black border around the pie chart is much fuller and rounder with antialiasing.
To set antialiasing, create a renderinghints object and pass it to the graphics2d setrenderinghints () Method as follows:
Renderinghints renderhints = new renderinghints (renderinghints. key_antialiasing,
Renderinghints. value_antialias_on );
G2d. setrenderinghints (renderhints );
Drawing a resizable border
The pie chart in figure A has a border and a drop shadow. ideally, it shoshould be possible to change the size of the drop shadow and border areas by changing only one variable. this is achieved by declaringInt border = 10And then basing all calculations for the size of the border area on this variable:
Ellipse2d. Double ELB = new ellipse2d. Double (x_pie-border/2, y_pie-border/2, piewidth + border, pieheight + border );
The values x_pie and y_pie represent the top-left location of an imaginary square that surrounds the pie chart. we center the pie chart's border by dividing the border variable by two (border/2).
Arc Theory
The fillarc () method, which is inherited from the java. AWT. graphics class, provides a simple mechanic for drawing the pie "slices," or arcs:
G2d. fillarc (x_position, y_position, width, height, startangle, sweepangle );
The x_position AndY_position integers represent the X and Y coordinates of the upper-left corner of the arc to be filled. the width and height integers provide its dimensions. if the width and height values are equal, the pie chart will be round. if the width and height are not equal, the pie chart will have an oval shape.
The position of the ARC'sStartangleIs determined relative to zero degrees, which is located at the horizontal, 3 O 'clock position. degrees are arranged counterclockwise around the pie chart, so 90 degrees is found at 12 o'clock, 180 degrees at 9 o 'clock and 270 degrees is located at the 6 o'clock position.
The fillarc () method Determines the size of the Arc Based on the sweepangle integer value. arcs are drawn counterclockwise if the sweepangle is positive and clockwise if it is negative.
Drawing the arcs
First, we use the piecolor Object's getpiecolor () method to get the latest pie color and assign it to the current slice:
G2d. setcolor (PC. getpiecolor ());
Next, we calculate the overall sales total by looping through the sales [] array and incrementing the sales total:
Salestotal + = Sales [I];
Using the sales total, it is possible to calculate the total sales for each product as a percentage of the total sales:
Float Perc = (sales [I]/salestotal );
We calculate the sweepangle (out of a total of 360 degrees) to allocate to each individual slice:
Int sweepangle = (INT) (PERC * 360 );
After each arc is drawn, the startangle is incremented with the current sweepangle. This ensures that each arc starts drawing where the last arc ended, creating a seamless pie chart.
Displaying the legend
A legend offers a concise way of displaying Summary figures on a pie chart. A legend shoshould be color-coded to match the elements of the pie chart.
Figure BShows the complete pie chart and the legend, which displays product names, sales totals, and percentages in a summarised format.
Have a slice
This article has encoded ed the basics of pie charts by providing techniques and algorithms Any programmer can use. The complete JSP for this article is already ded inListing E.