这里将JFreeChart结合struts2,演示在JSP页面局部刷新JFreeChart图。
一、创建Action类
public class ChartAction extends ActionSupport
{
/**
* serialVersionUID long
*/
private static final long serialVersionUID = 1320365631214252470L;
private JFreeChart chart;
public JFreeChart getChart(){
chart = ChartFactory.createBarChart(
"小组投票统计图", //图表标题
"组员", //目录轴的显示标签
"得分", //数值轴的显示标签
getDataSet(), //数据集
PlotOrientation.VERTICAL, //图表方向:垂直
false, //是否显示图例(对于简单的柱状图必须是false)
false, //是否显示工具提示
false //是否生成URL
);
chart.setTitle(new TextTitle("小组投票统计图 -- " + new Date().toLocaleString(), new Font("黑体", Font.ITALIC, 22)));
CategoryPlot plot = (CategoryPlot)chart.getPlot();//获得横轴
CategoryAxis categoryAxis = plot.getDomainAxis(); //设置横轴显示标签的字体
categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 22)); //分类标签以45度角倾斜
//categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 18)); //获得纵轴
NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis(); //设置纵轴显示标签的字体
numberAxis.setLabelFont(newFont("宋体", Font.BOLD, 22));
return chart;
}
private static CategoryDataset getDataSet(){
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
dataSet.setValue(200, "", "zhangsan");
dataSet.setValue(160, "", "lisi");
dataSet.setValue(175, "", "wangwu");
dataSet.setValue(210, "", "zhaoliu");
dataSet.setValue(200, "", "huqi");
return dataSet;
}
}
二、配置Action
<struts>
<package name="struts2" extends="jfreechart-default">
<action name="voteChart">
<result type="chart">
<param name="width">600</param>
<param name="height">450</param>
</result>
</action>
</package>
</struts>
注意,这里extends了jfreechart-default,而不是“struts-default”,是因为我修改了struts2-jfreechart-plugin-2.0.11.1.jar
中的struts-plugin.xml:
<package name="jfreechart-default" extends="struts-default">
<result-types>
<result-type name="chart">
<param name="height">150</param>
<param name="width">200</param>
</result-type>
</result-types>
</package>
三、整理JSP页面
<html>
<head>
<title>Test refresh chart</title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function viewChart(){
var random = Math.floor(Math.random()*10000 + 1);
$("#imageDiv1").attr("src","voteChart.action?"+ random);
}
//setInterval("viewChart()", 5000);
</script>
</head>
<body>
Enter page time:
<% Date date = new Date();
String time = date.toLocaleString(); %>
<%=time %><br>
<div style="margin-top:100px;">
View the Pie Chart:
<input type="button" value="View" οnclick="viewChart();"/><br/>
<img id="imageDiv1" src=""></img>
</div>
</body>
</html>
其中$("#imageDiv1").attr("src","voteChart.action?" + random); 中的random不能少,否则不能刷新。
启动服务器,打开页面,可以看到: