基於web的jfreechart的使用,webjfreechart

來源:互聯網
上載者:User

基於web的jfreechart的使用,webjfreechart

這個模組的主要步驟就是:

前台通過struts調用後台,通過JFreeChart產生圖片格式的圖表,儲存在某個位置,然後前台jsp再去調用圖片。


來開工。
JFreeChart的簡介大家請百度。
首先需要兩個包,jcommon-1.0.16.jar和jfreechart-1.0.13.jar。
jfreechart(下面就簡稱jfc),有可能會出現中午亂碼問題,我建議大家就找上面那兩個包,至少不會出那些需要換包的問題。

先看看效果

產生的圖片:

前台的顯示效果:


背景方法

public String statistic() {        //.....        //diagramType就是前台的那個下拉框        //可以是餅狀圖也可以是柱狀圖        if (diagramType.equals("barChart"))            getBarChart();        else            getPieChart();                //getExcel(countArray);        return SUCCESS;    }

    /**     * 產生柱狀圖     */    public void getBarChart() {        CategoryDataset dataset = getDataSet();// 擷取資料結果集        JFreeChart chart = ChartFactory.createStackedBarChart3D("不同危險等級病人數分布", // 標題                "危險等級",// x軸顯示                "病人數量(單位:位)", // y軸顯示                dataset, // 資料來源                PlotOrientation.VERTICAL, // 圖表方向:水平,垂直                true, // 是否顯示圖例(對於簡單的柱狀圖必須是false)                false,// 是否產生工具                false);// 是否產生URL連結        CategoryPlot plot = chart.getCategoryPlot();        CategoryAxis axis = plot.getDomainAxis(); // 擷取X軸        ValueAxis numberAxis = plot.getRangeAxis();// 擷取y軸        axis.setLowerMargin(0.06);// 設定距離圖片左端距離此時為6%        axis.setUpperMargin(0.06); // 設定距離圖片右端此時為6%        axis.setCategoryLabelPositionOffset(10);// 圖表橫軸與標籤的距離(10像素)        axis.setCategoryMargin(0.2);// 橫軸標籤之間的距離20%        chart.getLegend().setItemFont(new Font("黑體", Font.BOLD, 12));// 設定底部中文亂碼        axis.setTickLabelFont(new Font("黑體", Font.BOLD, 12));// 設定X軸座標上的文字        axis.setLabelFont(new Font("黑體", Font.BOLD, 14));// 設定X軸的標題文字        numberAxis.setTickLabelFont(new Font("黑體", Font.BOLD, 12));// 設定y軸座標上的文字        numberAxis.setLabelFont(new Font("黑體", Font.BOLD, 14));// 設定Y軸的標題文字        chart.getTitle().setFont(new Font("黑體", Font.BOLD, 18));// 設定標題文字                NumberAxis numberAxis1 = (NumberAxis)chart.getCategoryPlot().getRangeAxis();        numberAxis1.setAutoTickUnitSelection(false);        numberAxis1.setTickUnit(new   NumberTickUnit(30D));//1為一個間隔單位                BarRenderer3D customBarRenderer = (BarRenderer3D) plot.getRenderer();        customBarRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());//顯示每個柱的數值        customBarRenderer.setBaseItemLabelsVisible(true); //柱子上數值可見        Date date = new Date();// 擷取目前時間        chartTimeTag = Long.toString(date.getTime());// 擷取目前時間的時間戳記        String path = ServletActionContext.getServletContext().getRealPath("/")                + "resources/chart/" + chartTimeTag + ".png";// 圖片的儲存路徑        // 輸出圖片到檔案        FileOutputStream fos_png = null;        try {            fos_png = new FileOutputStream(path);            ChartUtilities.writeChartAsPNG(fos_png, chart, 900, 500, null);// 儲存為png圖片,寬度為900,高為500            fos_png.close();        } catch (IOException e) {            e.printStackTrace();            logger.error(e.toString());        }    }

    /**     * 得到產生柱狀圖的資料結果集,將方法tongJi()所得到的結果集中的資料依次添加到dataset中     *     * @return dataset 返回柱狀圖所需要的資料結果集     */    public CategoryDataset getDataSet() {        DefaultCategoryDataset dataset = new DefaultCategoryDataset();        for (int i = 0; i < hosDegreeDataList.size(); i++) {            //hosDegreeDataList裡面存放的就是資料            //hosDegreeDataList是一個list 每個element都是一組資料            //大家對比一片中的ss與mm 就知道addValue的三個參數的作用了            dataset.addValue(Integer.parseInt(hosDegreeDataList.get(i).get(2)                    .toString()), hosDegreeDataList.get(i).get(0).toString()+"mm",                    hosDegreeDataList.get(i).get(0).toString()+"ss");  //加上ss與mm 你就知道這兩個參數的區別了        }        return dataset;    }

  /**     * 產生餅狀圖     */    public void getPieChart() {        System.out.println("create chart start!!!!!!!!!");        PieDataset dataset = getPieDataSet();// 擷取資料結果集        JFreeChart chart = ChartFactory.createPieChart3D("不同危險等級病人數分布",// 圖表標題                dataset,// 資料來源                true,// 是否顯示圖例                true, true);// 是否產生工具,是否產生URL連結        PiePlot3D plot = (PiePlot3D) chart.getPlot();        // 圖片中顯示百分比:預設        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(                StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));        // 圖片中顯示百分比:自訂方式,{0} 表示選項, {1} 表示數值,        // {2} 表示所佔比例 ,小數點後兩位        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(                "{0}={1}({2})", NumberFormat.getNumberInstance(),                new DecimalFormat("0.00%")));        // 圖例顯示百分比:自訂方式, {0} 表示選項, {1} 表示數值, {2} 表示所佔比例        plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));        // 指定圖片的透明度(0.0-1.0)        plot.setForegroundAlpha(1.0f);        // 指定顯示的餅圖上圓形(true)還橢圓形(false)        plot.setCircular(true);        // 設定圖上分類標籤label的字型,解決中文亂碼        plot.setLabelFont(new Font("黑體", Font.PLAIN, 12));        // 設定圖上分類標籤label的最大寬度,相對與plot的百分比        plot.setMaximumLabelWidth(0.2);        // 設定3D餅圖的Z軸高度(0.0~1.0)        plot.setDepthFactor(0.07);        // 設定起始角度,預設值為90,當為0時,起始值在3點鐘方向        plot.setStartAngle(45);        // 設定表徵圖題的字型,解決中文亂碼        TextTitle textTitle = chart.getTitle();        textTitle.setFont(new Font("黑體", Font.PLAIN, 20));        // 設定背景色為白色        chart.setBackgroundPaint(Color.white);        // 設定Legend部分字型,解決中文亂碼        chart.getLegend().setItemFont(new Font("宋體", Font.PLAIN, 12));        Date date = new Date();        chartTimeTag = Long.toString(date.getTime());// 擷取當前的時間戳記        String path = ServletActionContext.getServletContext().getRealPath("/")                  + "resources/chart/" + chartTimeTag + ".png";// 圖片的儲存路徑        // 輸出圖片到檔案        //+"resources/chart/abc.png";        System.out.println(path);        FileOutputStream fos_png = null;        try {            fos_png = new FileOutputStream(path);            ChartUtilities.writeChartAsPNG(fos_png, chart, 900, 500, null);            fos_png.close();        } catch (IOException e) {            e.printStackTrace();            logger.error(e.toString());        }    }

   /**     * 得到產生餅狀圖的資料結果集:將方法tongJi()所得到的結果集中的資料依次添加到dataset中     *     * @return dataset 返回餅狀圖所需要的資料結果集     */    public PieDataset getPieDataSet() {        DefaultPieDataset dataset = new DefaultPieDataset();        for (int i = 0; i < hosDegreeDataList.size(); i++) {            dataset.setValue(hosDegreeDataList.get(i).get(0).toString(), Double                    .parseDouble(hosDegreeDataList.get(i).get(2).toString()));        }        return dataset;    }


    返回的jsp頁面部分代碼如下:
  
  <img src="../../../resources/chart/<s:property value = "chartTimeTag"/>.png"                / width="500px">            <br>            <br>    <input type="button" class="btn_long" value="點擊查看大圖"            onclick="window.open('../../../resources/chart/<s:property value="chartTimeTag"/>.png')" />


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.