Easily implement data pie chart 4 on the JSP page

Source: Internet
Author: User
Appendix: all source code in this article

Listing E

<% @ Page language = "java" %>
<% @ Page import = "java. io. OutputStream" %>
<% @ Page import = "java. SQL. *" %>
<% @ Page import = "java. awt. *" %>
<% @ Page import = "java. awt. geom. *" %>
<% @ Page import = "java. awt. image. BufferedImage" %>
<% @ Page import = "com.sun.image.codec.jpeg. *" %>
<%!
//////////////////////////////////////// ////////////////////
// PieColors class manages the colors used in the pie chart
//////////////////////////////////////// ////////////////////
Class PieColors
{
Color pieColorArray [] = {
New Color (60,210, 60), new Color (210, 60), new Color (60, 60 ),
New Color (120, 60, 60,120,210), new Color (210,120), new Color (, 60)
};
Int curPieColor = 0;
Public Color getPieColor ()
{
Return pieColorArray [curPieColor];
}
Public void setNewColor ()
{
CurPieColor ++;
If (curPieColor> = pieColorArray. length)
{CurPieColor = 0 ;}
}
}
%>
<%! String driver = "com. mysql. jdbc. driver "; String dburl =" jdbc: mysql: // localhost/articles "; String dbuid =" myuid "; String dbpwd =" mypwd ";

//////////////////////////////////////// ////////////////////
// Get the products from the database as a String array
//////////////////////////////////////// ////////////////////
Public String [] getProducts ()
{
String [] arr = new String [0];
Connection con;
Statement stmt;
ResultSet rs;
Int count = 0;
String SQL = "select * from p_products order by productID ";
Try
{
// Load Driver:
Class. forName (driver );
// Connect to the database with the url
Con = DriverManager. getConnection (dburl, dbuid, dbpwd );
Stmt = con. createStatement ();
// Get ResultSet
Rs = stmt.exe cuteQuery (SQL );
// Count the records
While (rs. next () {count ++;
}
// Create an array of the correct size
Arr = new String [count];
// Get ResultSet (the most portable way of using rs a second time)
Rs = stmt.exe cuteQuery (SQL );
While (rs. next ())
{
Arr [rs. getInt ("productID")] = rs. getString ("productname ");
}
Stmt. Close ();
Con. Close ();
}
Catch (Java. Lang. Exception ex)
{Arr [0] = ex. tostring ();}
Return arr;
}
//////////////////////////////////////// ////////////////////
// Get the sales totals from the database
//////////////////////////////////////// ////////////////////
Public float [] getsales (INT products)
{
Float [] arr = new float [products];
Connection con;
Statement stmt;
Resultset RS;
String SQL = "select productid, amount from p_sales ";
Try {
// Load driver:
Class. forname (driver );
// Connect to the database with the URL
Con = drivermanager. getconnection (dburl, dbuid, dbpwd );
Stmt = con. createStatement ();
// Get ResultSet
Rs = stmt.exe cuteQuery (SQL );
While (rs. next () {int product = rs. getInt ("productID ");
// Check that the productID is valid
If (product> = 0 & product <products)
{
// Add to product total
Arr [product] + = rs. getFloat ("amount ");
}
}
Stmt. close ();
Con. close ();
} Catch (java. lang. Exception ex) {arr [0] =-1.0f ;}
Return arr ;}%>
<%
// Get an array that contains the product names
String products [] = getProducts ();
// Read the data and store the totals in an array
Float sales [] = getSales (products. length );
// Declare PieColors
Pc = new PieColors ();
// Colors Color
DropShadow = new Color (240,240,240 );
// Inner padding to make sure bars never touch the outer border
Int innerOffset = 20;
// Set the graph's outer width & height
Int WIDTH = 400;
Int HEIGHT = 200;
Int pieHeight = HEIGHT-(innerOffset * 2 );
Int pieWidth = pieHeight;
// To make a square (circular) pie
Int halfWidth = WIDTH/2;
// Width of the inner graphable area
Int innerWIDTH = WIDTH-(innerOffset * 2 );
// Graph dimensions Dimension
GraphDim = new Dimension (WIDTH, HEIGHT );
Rectangle graphRect = new Rectangle (graphDim );
// Border dimensions
Dimension borderDim = new Dimension (halfWidth-2, HEIGHT-2 );
Rectangle borderRect = new Rectangle (borderDim );

//////////////////////////////////////// /////////////////////
// Set up the graph
//////////////////////////////////////// ////////////////////
// Set content type
Response. setContentType ("image/jpeg ");
// Create BufferedImage & Graphics2D
BufferedImage bi = new BufferedImage (WIDTH, HEIGHT, BufferedImage. TYPE_INT_RGB );
Graphics2D g2d = bi. createGraphics ();
// Set Antialiasing RenderingHints
RenderHints = new RenderingHints (RenderingHints. KEY_ANTIALIASING, RenderingHints. VALUE_ANTIALIAS_ON );
G2d. setRenderingHints (renderHints );
// Set graph background color to white:
G2d. setColor (Color. white );
G2d. fill (graphRect );
// Draw black border
G2d. setcolor (color. Black );
Borderrect. setlocation (1, 1 );
G2d. Draw (borderrect );
// Now draw border for legend
Borderrect. setlocation (width/2) + 1, 1 );
G2d. Draw (borderrect );
//////////////////////////////////////// ////////////////////////////
// Draw data onto the graph:
//////////////////////////////////////// ////////////////////////////
Int x_pie = inneroffset;
Int y_pie = inneroffset; int border = 20;
// Main chart Ellipse
// Ellipse2d. double El = new ellipse2d. double (x_pie, y_pie, piewidth, pieheight); ellipse2d. double ELB = new ellipse2d. double (x_pie-border/2, y_pie-border/2, piewidth + border, pieheight + border );
// Shadow
G2d. setcolor (dropshadow );
G2d. Fill (ELB );
// Border
G2d. setcolor (color. Black );
G2d. Draw (ELB );

//////////////////////////////////////// /////////////////////////
// Calculate the total sales
//////////////////////////////////////// /////////////////////////
Float salestotal = 0.0f;
Int lastelement = 0;
For (INT I = 0; I <products. length; I ++)
{
If (sales [I]> 0.0f)
{
Salestotal + = Sales [I];
Lastelement = I;
}
}
//////////////////////////////////////// //////////////////////
// Draw the pie chart
//////////////////////////////////////// /////////////////////
// Chart Variables
Int startangle = 0;
// Legend Variables
Int legendWidth = 20;
Int x_legendText = halfWidth + innerOffset/2 + legendWidth + 5;
Int x_legendBar = halfWidth + innerOffset/2;
Int textHeight = 20;
Int curElement = 0;
Int y_legend = 0;
// Dimensions of the legend bar
Dimension legendDim = new Dimension (legendWidth, textHeight/2 );
Rectangle legendRect = new Rectangle (legendDim );
For (int I = 0; I <products. length; I ++)
{
If (sales [I]> 0.0f)
{
// Calculate percentage sales float
Perc = (sales [I]/salesTotal );
// Calculate new angle
Int sweepAngle = (int) (perc * 360 );
// Check that the last element goes back to 0 position
If (I = lastElement)
{
SweepAngle = 360-startAngle;
}
// Draw Arc
G2d. setColor (pc. getPieColor ());
G2d. fillArc (x_pie, y_pie, pieWidth, pieHeight, startAngle, sweepAngle );
// Increment startAngle with the sweepAngle
StartAngle + = sweepAngle;
/////////////
// Draw Legend
/////////////
// Set y position for bar
Y_legend = curElement * textHeight + innerOffset;
// Display the current product
String display = products [I];
G2d. setColor (Color. black );
G2d. drawString (display, x_legendText, y_legend );
// Display the total sales
Display = "" + (int) sales [I];
G2d. setColor (Color. black );
G2d. drawString (display, x_legendText + 80, y_legend );
// Display the sales percentage
Display = "(" + (int) (perc * 100) + "% )";
G2d. setColor (Color. red );
G2d. drawString (display, x_legendText + 110, y_legend );
// Draw the bar
G2d. setColor (pc. getPieColor ());
LegendRect. setLocation (x_legendBar, y_legend-textHeight/2 );
G2d. fill (legendRect );
// Set new pie color
Pc. setNewColor ();
// Increment
CurElement ++;
}
}
//////////////////////////////////////// ////////
// Encode the graph
/////////////////////////////////////////
OutputStream output = response. getOutputStream ();
Required imageencoder encoder = required codec. createJPEGEncoder (output );
Encoder. encode (bi );
Output. close (); %>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.