package demo;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
/**
* 生成两个日期间的以天为间隔的折线图
* @throws ParseException
*/
public class MyLineAndShapeChart {
public CategoryPlot getLineAndShapeChart() throws ParseException {
//准备生成数据源需要的要素
List<String> dateList = new ArrayList<String>();
List<Double> valList = new ArrayList<Double>();
String start = "2008-01-21";
String end = "2008-02-08";
//字符串转换成日期
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date startDate=format.parse(start);
Calendar startTime=Calendar.getInstance();
startTime.clear();
startTime.setTime(startDate);
int startYear = startTime.get(Calendar.YEAR);
int startMonth = startTime.get(Calendar.MONTH);
int startDay = startTime.get(Calendar.DAY_OF_MONTH);
Date endDate=format.parse(end);
Calendar endTime=Calendar.getInstance();
endTime.clear();
endTime.setTime(endDate);
int endYear = endTime.get(Calendar.YEAR);
int endMonth = endTime.get(Calendar.MONTH);
int endDay = endTime.get(Calendar.DAY_OF_MONTH);
System.out.println("注意西方的月份从0到11,中国的月份从1到12");
System.out.println("下面输入的是中国的日期.注意其中的转换问题");
System.out.println("start date : " + start);
System.out.println("end date : " + end);
int count = 0;
for (int x = startYear; x <= endYear; x++) {
//罗马历法产生年份公元1582年
int gregorianCutoverYear = 1582;
boolean isLeapYear = x >= gregorianCutoverYear ?
((x%4 == 0) && ((x%100 != 0) || (x%400 == 0))) :
(x%4 == 0);
//判断是否是闰年
//java方法
//boolean isLeapYear = (new GregorianCalendar()).isLeapYear(x);
String isBigYear = "是平年";
if (isLeapYear) {
isBigYear = "是闰年";
}
System.out.println(x + "年" + isBigYear);
//获取开始月的最大天数
//java方法
//SimpleDateFormat aFormat=new SimpleDateFormat("yyyy-MM-dd");
//Date date = aFormat.parse(start);
//Calendar time = Calendar.getInstance();
//time.clear();
//time.setTime(date);
//int max=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
//System.out.println(max);
//获取开始月的最大天数;大月是1,3,5,7,8,10,12;小月是4,6,9,11;特殊月是2
int max = 0;
if (startMonth == 1) {
if (isLeapYear) {
max = 29;
}
if (!isLeapYear) {
max = 28;
}
}
if (startMonth == 3 || startMonth == 5 || startMonth == 8 || startMonth == 10) {
max = 30;
}
if (startMonth == 0 || startMonth == 2 || startMonth == 4 || startMonth == 6 || startMonth == 7 || startMonth == 9 || startMonth == 11) {
max = 31;
}
//循环每个月
//如果在日期范围内月份循环时自增到了一年的最后一个月就将月份初始化到一月份
int y = 0;
//如果是开始日期的第一个年的月数就从开始月数循环
if (x == startYear) {
y = startMonth;
}
for (; y < 12; y++) {
//获取当月的最大天数;大月是1,3,5,7,8,10,12;小月是4,6,9,11;特殊月是2
max = 0;
if (y == 1) {
if (isLeapYear) {
max = 29;
}
if (!isLeapYear) {
max = 28;
}
}
if (y == 3 || y == 5 || y == 8 || y == 10) {
max = 30;
}
if (y == 0 || y == 2 || y == 4 || y == 6 || y == 7 || y == 9 || y == 11) {
max = 31;
}
int ty = y + 1;
System.out.println(x + "年" + ty + "月");
//循环每一天
int z = 1;
//如果是开始日期的第一个月的天数就从开始天数循环
if (x == startYear && y == startMonth) {
z = startDay;
}
for (; z <= max; z++) {
count++;
String str = x + "年" + ty + "月" + z + "日";//日期格式可以调整
System.out.println(str);
dateList.add(str);
double val = x + y * z * 100;//实际的值应该从数据库中获取
valList.add(new Double(val));
if (x == endYear && y == endMonth && z == endDay) {
break;
}
}
//如果已经遍历过了截至日期的最后月份就中止月份的循环
if (x == endYear && y == endMonth) {
break;
}
}
}
System.out.println(start + " 到 " + end + " 的天数差:" + count);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
String[] rowKeys = { "上限值", "下限值", "重量" };
String[] columnKeys = new String[count];
double[][] data = new double[3][count];
for (int i = 0; i < count; i++) {
columnKeys[i] = dateList.get(i);
data[0][i] = 2500;
data[1][i] = 1500;
data[2][i] = valList.get(i).doubleValue();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);
JFreeChart chart = ChartFactory.createLineChart("工艺秤日称重重量趋势图", "日期", "总量",
dataset, PlotOrientation.VERTICAL, true, true, false);
chart.setTextAntiAlias(false);
chart.setBackgroundPaint(Color.WHITE);
// 设置图标题的字体重新设置title
Font font = new Font("隶书", Font.BOLD, 25);
TextTitle title = new TextTitle("工艺秤日称重重量趋势图");
title.setFont(font);
chart.setTitle(title);
// 设置面板字体
Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
chart.setBackgroundPaint(Color.WHITE);
CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
// x轴 // 分类轴网格是否可见
categoryplot.setDomainGridlinesVisible(true);
// y轴 //数据轴网格是否可见
categoryplot.setRangeGridlinesVisible(true);
categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩
categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩
categoryplot.setBackgroundPaint(Color.lightGray);
// 设置轴和面板之间的距离
// categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
CategoryAxis domainAxis = categoryplot.getDomainAxis();
domainAxis.setLabelFont(labelFont);// 轴标题
domainAxis.setTickLabelFont(labelFont);// 轴数值
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的
// Lable
// 45度倾斜
// 设置距离图片左端距离
domainAxis.setLowerMargin(0.0);
// 设置距离图片右端距离
domainAxis.setUpperMargin(0.0);
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
numberaxis.setAutoRangeIncludesZero(true);
// 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot
.getRenderer();
lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见
// 显示折点数据
// lineandshaperenderer.setBaseItemLabelGenerator(new
// StandardCategoryItemLabelGenerator());
// lineandshaperenderer.setBaseItemLabelsVisible(true);
//打印到服务器
FileOutputStream fos_jpg = null;
//String dirs = "C:/workspace/test/map/";
String dirs = "F:/test/";
String fileName = "lineAndShap.png";
String chartName = dirs + fileName;
try {
File file = new File(dirs);
if (!file.exists()) {
file.mkdirs();
}
fos_jpg = new FileOutputStream(chartName);
// 将报表保存为png文件
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 1500, 510);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
fos_jpg.close();
System.out.println("ok");
} catch (Exception e) {
e.printStackTrace();
}
}
//输出到浏览器
return categoryplot;
}
servlet的doGet方法中代码
response.setContentType("text/html");
System.out.println("line");
String factory = request.getParameter("factory");
System.out.println(factory);
MyLineAndShapeChart my = new MyLineAndShapeChart();
CategoryPlot mm = new CategoryPlot();
try {
mm = my.getLineAndShapeChart();
} catch (ParseException e) {
e.printStackTrace();
}
JFreeChart chart = new JFreeChart("ssssssss", JFreeChart.DEFAULT_TITLE_FONT,
mm, true);
ChartRenderingInfo info = new ChartRenderingInfo(
new StandardEntityCollection());
String filename = ServletUtilities.saveChartAsPNG(chart, 500, 300,
info, request.getSession());
String graphURL = request.getContextPath()
+ "/servlet/DisplayChart?filename=" + filename;
RequestDispatcher rd = request.getRequestDispatcher("../form/g.jsp");
request.getSession().setAttribute("filename", filename);
request.getSession().setAttribute("graphURL", graphURL);
rd.forward(request, response);
webInfo下的g.jsp代码
<%@ page contentType="text/html;charset=GBK"%>
<HTML>
<HEAD>
</HEAD>
<BODY>
<P ALIGN="CENTER">
<img src="${graphURL}" width=500 height=300 border=0
usemap="${filename}">
</P>
</BODY>
</HTML>
web.xml 文件中内容(重要)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>DisplayChart</servlet-name>
<servlet-class>
org.jfree.chart.servlet.DisplayChart
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/servlet/DisplayChart</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>AServlet</servlet-name>
<servlet-class>servlet.AServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AServlet</servlet-name>
<url-pattern>/servlet/AServlet</url-pattern>
</servlet-mapping>
</web-app>
柳德才
13691193654
18942949207
QQ:422157370
liudecai_zan@126.com湖北-武汉-江夏-庙山