Using JFreeChart in JSF

阅读更多
關于JFreeChart的介紹和JFreeChart的研究在網上到處都是,但是我發現沒有在JSF項目中使用的,今天我來說說我在JSF項目中如何動態創建JFreeChart的吧

第一步:
創建JFreeChart 中的BarChart和Linechart:兩個類與之對應并使用它們其中的init方法來創建,具體如何創建兩個chart代碼我就不寫了.

第二步:
第一步中創建了兩個類:BarChart和LineChart,并讓它們提供了兩個構建chart的靜態方法initBarChart和initLineChart.
接著通過使用JBoss的a4j:mediaOutput組件來在頁面上呈現所生成的圖片,并使用JFreeChart提供的ChartUtilities.writeImageMap()和ChartUtilities.getImageMap()生成并獲取到與生成的圖片對應的map,這樣就達到了在圖片上點選節點的時候顯示你所設定好的詳細信息了

backingbean和jsp的代碼如下:


JSF backingbean

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.faces.event.ActionEvent;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;

public class JFreeChartBean {

	private JFreeChart chart;
	
	private String mapCode;
	
	private ByteArrayOutputStream outputStream;

	public JFreeChartBean() {
		
	}

	public void selectBarChart(ActionEvent e) {
		chart = BarChart.initBarChart();
	}

	public void selectLineChart(ActionEvent e) {
		chart = LineChart.initLineChart();
	}
         //a4j:mediaOutput組件創建圖片的方法
	public void paint(OutputStream out, Object object) throws IOException {
		try {
			byte[] b = outputStream.toByteArray();
			out.write(b);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public JFreeChart getChart() {
		if (chart == null) {
			chart = BarChart.initBarChart();
		}
		return chart;
	}

	public void setChart(JFreeChart chart) {
		this.chart = chart;
	}
	//獲取到與生成的圖片對應的map
	public String getMapCode() {
		PrintWriter pw = null;
		try {
			ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
			outputStream = new ByteArrayOutputStream();
			ChartUtilities.writeChartAsPNG(outputStream,getChart(),500,300, info);
			pw = new PrintWriter(outputStream);
			ChartUtilities.writeImageMap(pw, "imgMap", info, false);
			mapCode = ChartUtilities.getImageMap("imgMap", info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mapCode;
	}

	
	public void setMapCode(String mapCode) {
		this.mapCode = mapCode;
	}
    


chart.jsp

    

		
		
		
		
		
		 
	



ps:上面的代碼沒有配置額外的servlet



例圖:

 

 

 

你可能感兴趣的:(jfreechart,JSF,Gmail,JSP,JBoss)