显示效果:
先引入相关的jar包:
jcommon-1.0.12.jar jfreechart-1.0.9.jar struts2-jfreechart-plugin-2.1.6.jar
package com.example.struts.action;
import jfreeChart.JfreeChartTest;
import org.jfree.chart.JFreeChart;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class JfreeCharAction extends ActionSupport {
/**
* 定义JFreeChart对象 大家请注意在这里JFreeChart对象名只能为chart
* 不能是别的
* 关于这点
* 大家可以上struts2网站上面查看一下
*
* http://struts.apache.org/2.x/docs/jfreechart-plugin.html
*/
private JFreeChart chart;
public JFreeChart getChart() {
return chart;
}
public void setChart(JFreeChart chart) {
this.chart = chart;
}
@Override
public String execute() throws Exception {
// 调用方法
this.chart = JfreeChartTest.createChart();
return SUCCESS;
}
}
package jfreeChart;
import java.awt.Font;
import java.io.IOException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
public class JfreeChartTest {
public static JFreeChart createChart() throws IOException {
// 数据集
DefaultPieDataset dpd = new DefaultPieDataset();
dpd.setValue("管理人员", 25);
dpd.setValue("市场人员", 25);
dpd.setValue("开发人员", 45);
dpd.setValue("其它人员", 10);
// 创建PieChart对象
JFreeChart chart = ChartFactory.createPieChart3D("某公司人员组织结构图", dpd,
true, true, false);
utils.setFont(chart);
return chart;
}
}
/**
* 设置字体
*
* @author zyong
*
*/
class utils {
public static void setFont(JFreeChart chart) {
Font font = new Font("宋体", Font.ITALIC, 12);
PiePlot plot = (PiePlot) chart.getPlot();
chart.getTitle().setFont(font);
plot.setLabelFont(font);
chart.getLegend().setItemFont(font);
}
}
<struts> <!-- 关于extends继承jfreechart-default这点请大家注意 因为在struts-default这个包里并没有result-type为chart的 chart 定义在前面我们导入的struts2-jfreechart-plugin-2.1.6.jar 下面的struts-plugin.xml文件中 --> <package name="jfreechart" extends="jfreechart-default"> <action name="jfreechart" class="com.example.struts.action.JfreeCharAction"> <result name="success" type="chart"> <param name="width">600</param> <param name="height">400</param> </result> </action> </package> </struts>