因为项目需要所以开始搞Java和JFreeChart类库…真蛋疼,看了51cto的该类库专题:http://developer.51cto.com/art/201112/309201.htm,这是最基本的,不懂JFreeChart的朋友请先移步此处。
很不错,讲得比较清楚,只是和官方发布的demo有些重合了吧,都是pieChart,敢换一个别的图吗?
下面我把画图所必须的三个模块列出来,其他的部分就不一一提供了,有需要的可以看看:
- //加载dataset,具体的业务逻辑可以不用理会
- public static XYDataset createxydataset(ArrayList<LineInfo> xydatalist, ArrayListMultimap<Integer, Integer> tabBat) {
- DefaultXYDataset dataset = new DefaultXYDataset();
- LineInfo tabTmp = xydatalist.get(0);
- int numTmp = tabTmp.getMeterNum();
- Set<Integer> allKey = tabBat.keySet();
- Iterator<Integer> it = allKey.iterator();
- int keyTmp = 0;
- while(it.hasNext())
- {
- keyTmp = it.next();
- if(tabBat.containsEntry(keyTmp, numTmp))
- break;
- }
- List<Integer> allNum = tabBat.get(keyTmp);
- int allNumSize = allNum.size();
- //data是数据的核心
- double[][] data = new double[2][allNumSize];
- it = allNum.iterator();
- Iterator<LineInfo> it2 = xydatalist.iterator();
- int tmp = 0, count = 0;
- LineInfo lineTmp = new LineInfo();
- while(it.hasNext())
- {
- tmp = it.next();
- it2 = xydatalist.iterator();
- while(it2.hasNext())
- {
- lineTmp = it2.next();
- if(tmp == lineTmp.getMeterNum())
- break;
- }
- data[0][count] = lineTmp.getIntercept();
- data[1][count] = lineTmp.getSlope();
- count++;
- }
- //addSeries里的第一个参数我还不太懂,从生成的图表看,就是图表下的说明文字而已
- dataset.addSeries("table", data);
- return dataset;
- }
- //生成图表对象
- public static JFreeChart createChart(XYDataset xydataset, String title, String xAxis, String yAxis) {
- JFreeChart scatterChart = ChartFactory.createScatterPlot(title, xAxis, yAxis, xydataset, PlotOrientation.VERTICAL, true, false, false);
- return scatterChart;
- }
- //根据图表对象,设置图像参数并画图,这里很重要,稍不注意,图里的文字就全是乱码了
- public static void drawScatterChart(JFreeChart scatterChart, String title, String noDataMsg) {
- //title, legend, plot 三个部分设置字体的方法分别如下:
- TextTitle textTitle = scatterChart.getTitle();
- textTitle.setFont(new Font("宋体", Font.BOLD, 20));
- LegendTitle legend = scatterChart.getLegend();
- if (legend != null)
- {
- legend.setItemFont(new Font("宋体", Font.BOLD, 20));
- }
- XYPlot scatterPlot = scatterChart.getXYPlot();
- scatterPlot.setNoDataMessage(noDataMsg);
- //以下三行是画图
- ChartFrame scatterFrame = new ChartFrame(title,scatterChart);
- scatterFrame.pack();
- scatterFrame.setVisible(true);
- }
总的来说,还是蛮简单的,要画其他的图去查一下API就可以了。