JFreeChart繪製保存爲圖片

配置好web.xml和struts.xml文件後,創建一個java文件繼承ActionSupport

public class Mchart extends ActionSupport{
@Override
public String execute() throws Exception {
ActionContext ac=ActionContext.getContext();
ac.getSession().put("flag", "1");
DefaultPieDataset dpd = new DefaultPieDataset();
dpd.setValue("Android開發", 25);
dpd.setValue("Java 開發", 25);
dpd.setValue("測試", 45);
dpd.setValue("UI設計", 10);
JFreeChart chart = ChartFactory.createPieChart("某公司人員組織數據圖", dpd, true,
false, false);
chart.setTitle(new TextTitle("某公司人員組織數據圖", new Font("宋體", Font.BOLD
+ Font.ITALIC, 20)));
chart.setBorderVisible(false);
chart.setBackgroundImageAlpha(0.0f);
LegendTitle legend = chart.getLegend(0);// 設置Legend
legend.setItemFont(new Font("宋體", Font.BOLD, 14));
PiePlot plot = (PiePlot) chart.getPlot();// 設置Plot
plot.setNoDataMessage("當前數據爲空!");
plot.setLabelFont(new Font("隸書", Font.BOLD, 16));
plot.setLabelBackgroundPaint(null);
plot.setLabelOutlinePaint(null);
plot.setOutlinePaint(SystemColor.WHITE);
plot.setLabelShadowPaint(SystemColor.WHITE);
plot.setBackgroundPaint(SystemColor.WHITE);
plot.setBackgroundImageAlpha(0.0f);
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
("{0}:{2}"), NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%")));
String root = ServletActionContext.getServletContext().getRealPath(
"/tubiao" + File.separator + "data.png");
try {
ChartUtilities.saveChartAsPNG(new File(root), chart, 520, 250);
} catch (IOException e) {
e.printStackTrace();
} 
System.out.println("asfsdf");
return "success";
}
}


之後,在Jsp文件中直接調用圖片位置就可以了。

<%
 if(session.getAttribute("flag")==null || session.getAttribute("flag").equals(""))
 {
 
 String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":"
+ request.getServerPort() + path + "/";
response.sendRedirect(basePath + "pa/loading.action");
 
 
 }
 %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>the demo jsp title!</title>
</head>
<body>
<img src="http://localhost:8080/demo/tubiao/data.png" width="800" height="600">
</body>
</html>

運行效果圖如下:

醜了點,可以自己調整圖片大小。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章