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; }
<h:form id="jFreeChartForm"> <t:panelGrid columns="2"> <a4j:commandButton value="BarChart" immediate="true" actionListener="#{jFreeChartBean.selectBarChart}" reRender="outMap,chart,jFreeChartForm"/> <a4j:commandButton value="LineChart" immediate="true" actionListener="#{jFreeChartBean.selectLineChart}" reRender="outMap,chart,jFreeChartForm"/> </t:panelGrid> <a4j:mediaOutput id="chart" element="img" cacheable="false" session="false" ismap="true" usemap="#imgMap" createContent="#{jFreeChartBean.paint}" mimeType="image/jpeg"/> <t:outputText id="outMap" escape="false" value="#{jFreeChartBean2.mapCode}"></t:outputText> </h:form>