jfreechart生成折线图实例(修改鼠标提示内容)

来源:互联网 发布:淘宝如何登录店铺 编辑:程序博客网 时间:2024/05/18 15:07
package com.csair.gsms.client.view.transfer;


import java.awt.Color;
import java.awt.Font;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.experimental.chart.swt.ChartComposite;


import com.csair.gsms.client.common.util.DateUtil;
import com.csair.gsms.ghc.client.core.fltPsgrLugStatistics.FDLTrsConditionItem;
import com.csair.gsms.ghc.client.core.fltPsgrLugStatistics.FDLTrsCountInfoItem;


public class TransferPredictionChart extends Composite {


public static final String[] lineTitle = {"中转人数","vip人数","两舱人数"};
public static final Integer lineCount = 1;

private String chartTitle;
private List<Map<String,Integer>> transList = new ArrayList<Map<String,Integer>>();

/**
* 重载的构造方法
* @param parent 父面板
* @param style  样式
*/
public TransferPredictionChart(Composite parent, int style) {
super(parent, style);
createContents();
}

/**
* 根据查询条件生成图形的标题(格式:始发站三字码-中转站三字码-目的地三字码)
* @param conditionItem 查询条件
*/
public void setChartTitle(FDLTrsConditionItem conditionItem){
StringBuffer title = new StringBuffer();
String depCd,arvCD;
depCd = conditionItem.getdDepCd()==null?"":conditionItem.getdDepCd();
depCd = "".equals(depCd)?conditionItem.getiDepCd()==null?"":conditionItem.getiDepCd():depCd;

arvCD = conditionItem.getdArvCd()==null?"":conditionItem.getdArvCd();
arvCD = "".equals(arvCD)?conditionItem.getiArvCd()==null?"":conditionItem.getiArvCd():arvCD;

title.append("".equals(depCd)?"全部":depCd);
title.append("-");
title.append(conditionItem.getTransferCd());
title.append("-");
title.append("".equals(arvCD)?"全部":arvCD);
this.chartTitle = title.toString();
}

/**
* 创建布局内容
*/
private void createContents() {
GridLayout gridLayout = new GridLayout(1, false);
gridLayout.marginHeight = 2;
gridLayout.marginWidth = 2;
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
this.setLayout(gridLayout);

GridData gridData = new  GridData(SWT.FILL, SWT.FILL, false, false);
this.setLayoutData(gridData);
}

/**
* 2014-04-18 zlh
* 在界面加载曲线图
* @param datas 曲线图数据源记录
* @param conditionItem 查询条件对象
*/
public void loadChart(List<FDLTrsCountInfoItem> datas,FDLTrsConditionItem conditionItem){
Control[] control = this.getChildren();
for(int i=0;i<control.length;i++){//先销毁上次查询生成的图形
control[i].dispose();
}
//获取查询的天数
int days = DateUtil.diffDate(DateUtil.parseDate(conditionItem.getInEFltDt(), 
DateUtil.YEAR_TO_DAY),DateUtil.parseDate(conditionItem.getInSFltDt(), DateUtil.YEAR_TO_DAY));
if(days>0){//查询的天数在两天以上(含)才展示曲线图
this.dealRecord(datas);//将查询的数据封装生集合
//this.initRecord(conditionItem);
this.setChartTitle(conditionItem);//根据查询条件生成图形标题
JFreeChart chart = this.createLineChart(this.createDataSet(),days);
ChartComposite chartComposite = new ChartComposite(this, SWT.NONE,chart, true);

GridData gd_chart = new GridData(SWT.FILL, SWT.FILL, true,true);
gd_chart.heightHint = 300;
chartComposite.setLayoutData(gd_chart);

FillLayout fillLayout = new FillLayout();
            fillLayout.type = SWT.VERTICAL;
            chartComposite.setLayout(fillLayout);
            //this.redraw();
this.layout();
//this.getParent().layout();
}

}

/**
* 2014-04-18 zlh
* 将查询的中转航班数据按日期计算好,并封装到集合transList中
* @param datas 查询的中转航班数据
*/
@SuppressWarnings("unchecked")
public void dealRecord(List<FDLTrsCountInfoItem> datas){
transList.clear();
FDLTrsCountInfoItem record;
String fltDt;
int[] transCount = new int[TransferPredictionChart.lineCount];
Map<String,Integer>[] transMap = new Map[TransferPredictionChart.lineCount];
for(int i=0;i<TransferPredictionChart.lineCount;i++){
transMap[i] = new HashMap<String,Integer>();
}
for(int i=0;i<datas.size();i++){
record = datas.get(i);
fltDt = DateUtil.format(DateUtil.parseDate(record.getfFltDt()),DateUtil.YEAR_TO_DAY);//航班日期作为曲线图的横坐标
for(int k=0;k<TransferPredictionChart.lineCount;k++){
if(k==0) transCount[k] = record.getTransCount();//中转人数
if(k==1) transCount[k] = record.getPsgrCountOfVip();//vip中转人数
if(k==2) transCount[k] = record.getLiangChange();//两舱中转人数
}
for(int j=0;j<TransferPredictionChart.lineCount;j++){
if(null != transMap[j].get(fltDt)){
            transMap[j].put(fltDt, new Integer(transCount[j]+(Integer)transMap[j].get(fltDt).intValue()));
           }else{
            transMap[j].put(fltDt, new Integer(transCount[j]));
           }
}
}
for(int j=0;j<TransferPredictionChart.lineCount;j++){
transList.add(transMap[j]);
}
}

/**
* 初始化记录:对某天没有数据的设置其数据值为0
* @param conditionItem
*/
public void initRecord(FDLTrsConditionItem conditionItem){
Date end = DateUtil.parseDate(conditionItem.getInEFltDt(), DateUtil.YEAR_TO_DAY);
Date start = DateUtil.parseDate(conditionItem.getInSFltDt(), DateUtil.YEAR_TO_DAY);
Date temp = DateUtil.diffDate(start,1);
int days = DateUtil.diffDate(end,start)+1;
Map<String,Integer> transMap = new HashMap<String,Integer>();
for(int i=0;i<transList.size();i++){
transMap = transList.get(i);
temp = DateUtil.diffDate(start,1);
for(int j=0;j<days;j++){
temp = DateUtil.addDate(temp,1);
if(null == transMap.get(DateUtil.format(temp,DateUtil.YEAR_TO_DAY))){
transMap.put(DateUtil.format(temp,DateUtil.YEAR_TO_DAY), 0);
}
}
}
}
/**
* 2014-04-18 zlh
* 根据封装好的集合transList生成曲线图需要的数据集
* @return 返回生成曲线图的数据集
*/
@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
public TimeSeriesCollection createDataSet(){
TimeSeriesCollection dataSet = new TimeSeriesCollection();
Map<String,Integer> transMap = new HashMap<String,Integer>();
for(int i=0;i<transList.size();i++){
TimeSeries line = new TimeSeries(TransferPredictionChart.lineTitle[i],Day.class);
transMap = transList.get(i);
Set lineSet = transMap.entrySet();
            Iterator lineIterator = lineSet.iterator();
            while(lineIterator.hasNext()){
                Map.Entry<String,Integer> hiddenMapEntry = (Map.Entry<String,Integer>)lineIterator.next();
                String key = hiddenMapEntry.getKey();
                int ye = Integer.parseInt(key.substring(0, 4));
                int mon = Integer.parseInt(key.substring(5, 7));
                int day = Integer.parseInt(key.substring(8, 10));
                Day days = new Day(day, mon, ye);
                line.add(days,hiddenMapEntry.getValue());
            }
            dataSet.addSeries(line);
}
return dataSet;
}

/**
* 2014-04-18 zlh
* 绘制曲线图
* @param dataset 曲线图数据集
* @param days 查询的天数(最少1天,最多3个月)
* @return 返回曲线图形
*/
public JFreeChart createLineChart(TimeSeriesCollection dataset,int days) {
ChartFactory.setChartTheme(this.getChartTheme());//设置主题样式
JFreeChart lineChart = ChartFactory.createTimeSeriesChart(this.chartTitle, "", "",dataset, true, true, false);

XYPlot xyplot = (XYPlot)lineChart.getXYPlot();
        this.setXYPlot(xyplot);//图形网格等辅助线设置
this.setNumberAxis(xyplot);//Y轴设置
this.setDateAxis(xyplot,days);//X轴设置
        this.setXYlineAndShapeRenderer(xyplot);//图形线条本身设置
        return lineChart;
}

/**
* 2014-04-24 zlh
* 设置图形标题、X轴、Y轴等字体的样式
* @return
*/
public StandardChartTheme getChartTheme(){
StandardChartTheme mChartTheme = new StandardChartTheme("CN");//防止中午乱码
mChartTheme.setLargeFont(new Font("黑体", Font.BOLD, 18));
mChartTheme.setExtraLargeFont(new Font("宋体", Font.PLAIN, 13));
mChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 13));
return mChartTheme;
}

/**
* 2014-04-24 zlh
* 设置图形区域的样式
* @param chart 图形区域对象
*/
public void setChartArea(JFreeChart chart){
chart.setBackgroundPaint(new Color(241,244,247));//背景色
}

/**
* 2014-04-24 zlh
* 线条背景辅助线设置
* @param xyplot
*/
public void setXYPlot(XYPlot xyplot){
xyplot.setBackgroundPaint(Color.white);//设置网格背景颜色 
xyplot.setDomainGridlinePaint(Color.lightGray);//设置网格竖线颜色 
xyplot.setDomainGridlinesVisible(false);//设置背景线的竖线显示
xyplot.setRangeGridlinePaint(Color.lightGray);//设置网格横线颜色 
xyplot.setRangeGridlinesVisible(true);//设置背景线的横线显示
}

/**
* 2014-04-24 zlh
* 线条设置
* @param xyplot
*/
@SuppressWarnings("deprecation")
public void setXYlineAndShapeRenderer(XYPlot xyplot){
XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)xyplot.getRenderer();
        //设置第一条曲线颜色
        xylineandshaperenderer.setSeriesPaint(0, Color.BLUE);
        //设置曲线是否显示实心数据点 
        xylineandshaperenderer.setShapesVisible(true);
        xylineandshaperenderer.setShapesFilled(true);
        //xylineandshaperenderer.setShape(new Rectangle(5, 5));
        
        //设置曲线显示各数据点的值 
        xylineandshaperenderer.setBaseItemLabelsVisible(true);
        
        //设置鼠标提示信息内容格式 (格式如:14年4月24:100人)
        StandardXYToolTipGenerator tipGenerator = new StandardXYToolTipGenerator("{1}:{2}人",
        new SimpleDateFormat("yy年MM月dd"),NumberFormat.getNumberInstance());
        xylineandshaperenderer.setToolTipGenerator(tipGenerator);
        
        //设置在折线点直接显示数据值,并可以指定位置
        /*xylineandshaperenderer.setBasePositiveItemLabelPosition(
        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
        xylineandshaperenderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
        xylineandshaperenderer.setBaseItemLabelPaint(new Color(102, 102, 102));// 显示折点数值字体的颜色  */
}

/**
* 2014-04-24 zlh
* X轴设置
* @param xyplot
* @param days
*/
@SuppressWarnings("deprecation")
public void setDateAxis(XYPlot xyplot,int days){
        DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
        dateaxis.setVerticalTickLabels(true);//横坐标竖直显示
        //设置横轴坐标显示样式
        SimpleDateFormat format = new SimpleDateFormat("MM-dd");
        
        //设置横坐标间隔天数
        if(days>60){//查询天数大于60天时候,横坐标间隔设置为两天
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 2, format));
        }else{
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 1, format));
        }
}

/**
* 2014-04-24 zlh
* Y轴设置
* @param xyplot
*/
public void setNumberAxis(XYPlot xyplot){
NumberAxis numAxis = (NumberAxis) xyplot.getRangeAxis();
NumberFormat numFormater = NumberFormat.getNumberInstance();
numFormater.setParseIntegerOnly(true);
numAxis.setNumberFormatOverride(numFormater);
}
}
0 0
原创粉丝点击