JFreeChart使用初步

xiaoxiao2023-02-02  52

jfreechart 写道 JFreeChart是JAVA平台上的一个开放的图表绘制类库。它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。JFreeChart可生成饼图(pie charts)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(Gantt charts)等等多种图表,并且可以产生PNG和JPEG格式的输出,还可以与PDF和EXCEL关联。

 

要使用JFreeChart , 只需要导入2个包, jcommon-xxx.jar 和 jfreechart-xxx.jar

这里我只使用jfreechart的3种图,分别是饼状图,柱状图,折线图。代码中提供了jfreechart的2种图表导出方式,一种是直接导出到本地磁盘形成图片,另一种是与struts2结合,直接联入页面中。

 

代码的结构为:

JFreeChartTest ==src ==action ==BarAction.java //柱状图 ==LineAction.java //折线图 ==PieAction.java //饼状图 ==createchart ==CreatePieBarChart.java //饼状图 ==CreatePieBarChart.java //饼状图 ==CreatePieBarChart.java //饼状图 ==pojo ==dao和pojo //数据源 ==struts.xml ==hibernate.cfg.xml ==struts.properties ==页面

 BarAction.java

public class BarAction extends ActionSupport{ private JFreeChart chart; public JFreeChart getChart() { JfreechartDAO jfcDAO = new JfreechartDAO(); List allList = jfcDAO.findAll(); CreateBarChart cpc = new CreateBarChart("水果图", allList, "D:/"); chart = cpc.createBar(); return chart; //用于在页面上显示 } }

 

另外2个action和上面的类似

 

CreateBarChart.java  柱状图

public class CreateBarChart { /** * 标题 */ private String title; /** * 生成的图片的存储路径 */ private final String SAVE_PATH; /** * 数据源 */ private List dataSource; public CreateBarChart(String title, List dataSource, final String savePath){ this.title = title; this.dataSource = dataSource; this.SAVE_PATH = savePath; } /** * 柱状图 */ public JFreeChart createBar() { JFreeChart chart = ChartFactory.createBarChart(this.title, // 图表标题 "水果种类", // 目录轴的显示标签 "数量", // 数值轴的显示标签 this.getDateset(this.dataSource), // 数据集 PlotOrientation.VERTICAL, // 图表方向:水平、垂直 false, // 是否显示图例(对于简单的柱状图必须是false) false, // 是否生成工具 false // 是否生成URL链接 ); Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); /* * VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭, * 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看 */ // chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); chart.setTextAntiAlias(false); chart.setBackgroundPaint(Color.gray); chart.getTitle().setFont(new Font("SansSerif", Font.TRUETYPE_FONT, 12)); // create plot CategoryPlot plot = chart.getCategoryPlot(); // 设置横虚线可见 plot.setRangeGridlinesVisible(true); // 虚线色彩 plot.setRangeGridlinePaint(Color.gray); // 数据轴精度 NumberAxis vn = (NumberAxis) plot.getRangeAxis(); // vn.setAutoRangeIncludesZero(true); DecimalFormat df = new DecimalFormat("#0"); vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式 // x轴设置 CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setLabelFont(labelFont);// 轴标题 domainAxis.setTickLabelFont(labelFont);// 轴数值 // Lable(Math.PI/3.0)度倾斜 // domainAxis.setCategoryLabelPositions(CategoryLabelPositions // .createUpRotationLabelPositions(Math.PI / 3.0)); domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示 // 设置距离图片左端距离 domainAxis.setLowerMargin(0.1); // 设置距离图片右端距离 domainAxis.setUpperMargin(0.1); // 设置 columnKey 是否间隔显示 // domainAxis.setSkipCategoryLabelsToFit(true); plot.setDomainAxis(domainAxis); // 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确) plot.setBackgroundPaint(new Color(255, 255, 204)); // y轴设置 ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setLabelFont(labelFont); rangeAxis.setTickLabelFont(labelFont); // 设置最高的一个 Item 与图片顶端的距离 rangeAxis.setUpperMargin(0.15); // 设置最低的一个 Item 与图片底端的距离 rangeAxis.setLowerMargin(0.15); plot.setRangeAxis(rangeAxis); BarRenderer renderer = new BarRenderer(); // 设置柱子宽度 renderer.setMaximumBarWidth(0.05); // 设置柱子高度 renderer.setMinimumBarLength(0.2); // 设置柱子边框颜色 renderer.setBaseOutlinePaint(Color.BLACK); // 设置柱子边框可见 renderer.setDrawBarOutline(true); // // 设置柱的颜色 renderer.setSeriesPaint(0, new Color(204, 255, 255)); renderer.setSeriesPaint(1, new Color(153, 204, 255)); renderer.setSeriesPaint(2, new Color(51, 204, 204)); // 设置每个地区所包含的平行柱的之间距离 renderer.setItemMargin(0.0); // 显示每个柱的数值,并修改该数值的字体属性 renderer.setIncludeBaseInRange(true); renderer .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setBaseItemLabelsVisible(true); plot.setRenderer(renderer); // 设置柱的透明度 plot.setForegroundAlpha(1.0f); FileOutputStream fos_jpg = null; try { isChartPathExist(this.SAVE_PATH); String chartName = SAVE_PATH + "bar.jpg"; fos_jpg = new FileOutputStream(chartName); ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 300, true, 10); return chart; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); System.out.println("create bar-chart."); } catch (Exception e) { e.printStackTrace(); } } } /** * 获得数据源 * @param dataSet * @return */ private CategoryDataset getDateset(List dataSet){ DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Jfreechart jfc = new Jfreechart(); for(int i = 0; i < dataSet.size(); i++){ jfc = (Jfreechart) dataSet.get(i); dataset.addValue(jfc.getAmount(),"", jfc.getName()); } return dataset; } /** * 判断文件夹是否存在,如果不存在则新建 * @param chartPath */ private void isChartPathExist(String chartPath) { File file = new File(chartPath); if (!file.exists()) { file.mkdirs(); // log.info("CHART_PATH="+CHART_PATH+"create."); } } }

 

CreateLineChart.java  折线图

public class CreateLineChart { /** * 标题 */ private String title; /** * 生成的图片的存储路径 */ private final String SAVE_PATH; /** * 数据源 */ private List dataSource; public CreateLineChart(String title, List dataSource, final String savePath){ this.title = title; this.dataSource = dataSource; this.SAVE_PATH = savePath; } public JFreeChart createLine(){ JFreeChart chart = ChartFactory.createLineChart(title, "序号", "数量", this.getDateset(this.dataSource), PlotOrientation.VERTICAL, false, false, false); chart.setTextAntiAlias(false); chart.setBackgroundPaint(Color.WHITE); // 设置图标题的字体重新设置title Font font = new Font("SansSerif", Font.BOLD, 25); TextTitle xtitle = new TextTitle(title); xtitle.setFont(font); chart.setTitle(xtitle); // 设置面板字体 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); // y轴设置 ValueAxis rangeAxis = categoryplot.getRangeAxis(); rangeAxis.setLabelFont(labelFont); rangeAxis.setTickLabelFont(labelFont); 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; try { isChartPathExist(SAVE_PATH); String chartName = SAVE_PATH + "linePicture.jpg"; fos_jpg = new FileOutputStream(chartName); // 将报表保存为png文件 ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 400); return chart; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); System.out.println("create time-createTimeXYChar."); } catch (Exception e) { e.printStackTrace(); } } } /** * 获得数据源 * @param dataSet * @return */ private CategoryDataset getDateset(List dataSet){ DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Jfreechart jfc = new Jfreechart(); for(int i = 0; i < dataSet.size(); i++){ jfc = (Jfreechart) dataSet.get(i); dataset.addValue(jfc.getAmount(),"", jfc.getName()); } return dataset; } /** * 判断文件夹是否存在,如果不存在则新建 * @param chartPath */ private void isChartPathExist(String chartPath) { File file = new File(chartPath); if (!file.exists()) { file.mkdirs(); // log.info("CHART_PATH="+CHART_PATH+"create."); } }

 

CreatePieChart.java 饼状图

public class CreatePieChart { /** * 标题 */ private String title; /** * 生成的图片的存储路径 */ private final String SAVE_PATH; /** * 数据源 */ private List dataSource; public CreatePieChart(String title, List dataSource, final String savePath){ this.title = title; this.dataSource = dataSource; this.SAVE_PATH = savePath; } /** * 生成饼状图 * @param dataSet * @return */ public JFreeChart createPie(){ JFreeChart chart = ChartFactory.createPieChart3D(this.title, this.getDateset(this.dataSource), true, true, false); chart.setTextAntiAlias(false); chart.setBackgroundPaint(Color.gray); Font font = new Font("SansSerif", Font.BOLD, 18); TextTitle xtitle = new TextTitle(this.title); xtitle.setFont(font); chart.setTitle(xtitle); PiePlot3D plot = (PiePlot3D) chart.getPlot(); plot.setNoDataMessage("没有数据"); plot.setNoDataMessagePaint(Color.red); // 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位 plot.setLabelGenerator((PieSectionLabelGenerator) new StandardPieSectionLabelGenerator( "{0}={1}({2})", NumberFormat.getNumberInstance(), new DecimalFormat("0.00%"))); // 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例 plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator( "{0}={1}({2})")); //解决图片编码 plot.setLabelFont(new Font("SansSerif", Font.TRUETYPE_FONT, 12)); //解决图例编码 chart.getLegend().setItemFont(new Font("SansSerif", Font.TRUETYPE_FONT, 12)); plot.setForegroundAlpha(0.7f); FileOutputStream fos_jpg = null; try { // 文件夹不存在则创建 this.isChartPathExist(SAVE_PATH); fos_jpg = new FileOutputStream(SAVE_PATH + "piePicture.jpg"); // 高宽的设置影响椭圆饼图的形状 ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 300); return chart; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos_jpg.close(); System.out.println("create pie-chart."); } catch (Exception e) { e.printStackTrace(); } } } /** * 获得数据源 * @param dataSet * @return */ private PieDataset getDateset(List dataSet){ DefaultPieDataset dataset = new DefaultPieDataset(); Jfreechart jfc = new Jfreechart(); for(int i = 0; i < dataSet.size(); i++){ jfc = (Jfreechart) dataSet.get(i); dataset.setValue(jfc.getName(), jfc.getAmount()); } return dataset; } /** * 判断文件夹是否存在,如果不存在则新建 * @param chartPath */ private void isChartPathExist(String chartPath) { File file = new File(chartPath); if (!file.exists()) { file.mkdirs(); // log.info("CHART_PATH="+CHART_PATH+"create."); } }

 

struts.xml

<package name="com.jfreechart" extends="jfreechart-default"> <action name="pie" class="action.PieAction"> <result type="chart"> <param name="width">600</param> <param name="height">450</param> </result> </action> <action name="bar" class="action.BarAction"> <result type="chart"> <param name="width">600</param> <param name="height">450</param> </result> </action> <action name="line" class="action.LineAction"> <result type="chart"> <param name="width">600</param> <param name="height">450</param> </result> </action> </package>

 

 

TestJfreeChart.jsp

<body> <img src="bar.do" /> <img src="pie.do" /> <img src="line.do" /> </body>

 

相关资源:Java 面经手册·小傅哥(公众号:bugstack虫洞栈).pdf
转载请注明原文地址: https://www.6miu.com/read-4981074.html

最新回复(0)