Create a table "chart" in the database :
To draw a bar chart, we have used JFreeChart Library.
JFreeChart is a chart library used to generate different variety of charts.
Download jar file: jfreechart.jar and jcommon.jar
The class JDBCCategoryDataset provides the implementation over a database JDBC result set.
Its constructor consists of url, driver, user, pass to connect to the database.
The method executeQuery(query) executes the query against the existing database connection.
The class ChartFactory provides the utility methods for creating charts.
The method createBarChart3D() creates a vertical 3D bar chart.
The class PlotOrientation is used to indicate the orientation (horizontal or vertical) of a 2D plot.
The class ChartUtilities includes methods for converting charts to image formats (PNG and JPEG).
The method saveChartAsJPEG(new File("C:/chart.jpg") saves a chart to a file specified in JPEG format.
Example
<%@ page import= "java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="org.jfree.chart.ChartFactory" %>
<%@ page import="org.jfree.chart.ChartUtilities" %>
<%@ page import="org.jfree.chart.JFreeChart" %>
<%@ page import="org.jfree.chart.plot.PlotOrientation"%>
<%@ page import="org.jfree.data.*" %>
<%@ page import="org.jfree.data.jdbc.JDBCCategoryDataset"%>
<%
String query = "SELECT * from chart";
JDBCCategoryDataset dataset = new JDBCCategoryDataset("jdbc:mysql://localhost:3306/chart","com.mysql.jdbc.Driver","root","root");
dataset.executeQuery(query);
JFreeChart chart = ChartFactory .createBarChart3D("Test", "Id", "Score", dataset, PlotOrientation.VERTICAL, true, true, false);
try {
ChartUtilities.saveChartAsJPEG(new File("C:/chart.jpg"), chart, 400, 300);
}
catch (IOException e) {
System.out.println("Problem in creating chart.");
}
%>
To run the above example start the tomcat and enter in address bar :
http://localhost:8080/application/jsp/bar.jsp
No comments:
Post a Comment
Note: only a member of this blog may post a comment.