終於正式使用 jfreechar 了,真的好用

這是成果,不過遇到了一些困擾

  • tomcat+struts+tile+jfreechart 使用 response.getOutputStream() 會有問題
  • 使用 FileOutputStream 要注意路徑與會產生檔案的問題

    第一個問題是因為 struts+tile 的關係,應該是 tile 產生 html 的方式在的不同,所以我只好先產生圖檔再去 refer 它,但也因此產生第二個問題

    第二個問題比較麻煩,路徑的話只要
    servlet.getServletContext().getRealPath("");
    就可取得實際位置,再找個目錄放檔案;但產生的 temp 就不知道要如何處理了,困擾

        public synchronized final static String draw(ArrayList lst, String path) {

            if ((lst == null) || (lst.isEmpty())) {
                return "";
            }

            int i = 0;
            String title = "";
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            Iterator it = lst.iterator();
            while (it.hasNext()) {
                ChartForm chr = (ChartForm) it.next();
                if (chr.getCnt() > 0) {
                    String s = chr.getDay().substring(
                        chr.getDay().indexOf("月") + 1,
                        chr.getDay().indexOf("日"));
                    dataset.setValue(chr.getCnt(), chr.getM(), s);
                } else {
                    dataset.setValue(chr.getCnt(), chr.getM(), "");
                }

                i++;
                if (i == 1) {
                    title = chr.getDay()
                    .substring(0, chr.getDay().indexOf("月") + 1);
                }
            }
            // dataSet.setCategories(xAxisData);
            title += "家數圖";

            PlotOrientation plot = PlotOrientation.VERTICAL;
            JFreeChart chart = null;
            chart = ChartFactory.createBarChart(title, "日期", "家數",
                    dataset, plot, false, false, false);

            Date d = new Date();
            String s = d.toString();
            s = path + File.separator + "jpg" + File.separator
                    + s.replaceAll(" ", "_").replaceAll(":", "_")
                     + ".jpg";
            System.out.println(s);
            File f = new File(s);
            try {
                FileOutputStream ostream = new FileOutputStream(f);

                ChartUtilities.writeChartAsJPEG(
                    ostream, chart, 400, 300);

                ostream.close();
            } catch (IOException e) {

            }

            return f.getName();
        }
  • arrow
    arrow
      全站熱搜

      identical 發表在 痞客邦 留言(0) 人氣()