• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
cnsdhzzl
博客园    首页    新随笔    联系   管理    订阅  订阅
Jfreechart初案例--饼图

1.action

@Controller(value = "pieAction")
@Scope("prototype")
public class PieAction extends ActionSupport {
    @Autowired
    private PieService pieService;
    // 图表
    private JFreeChart jFreeChart;

    @Override
    public String execute() throws Exception {
        // 1准备数据集
        DefaultPieDataset pieDate = new DefaultPieDataset();
        // 2查询数据
        List<Pie> list = pieService.find();
        // 3循环放入数据集
        for (Pie pie : list) {
            pieDate.setValue(pie.getName(), pie.getNum());
        }
        // 设置主题及编码(省略主题设置)
        StandardChartTheme sct = new StandardChartTheme("CN");
        ChartFactory.setChartTheme(sct);
        // 生成char
        this.jFreeChart = ChartFactory.createPieChart3D("标题-测试", pieDate);
        
        // 乱码解决
        TextTitle textTitle = jFreeChart.getTitle();
        textTitle.setFont(new Font("微软雅黑", Font.BOLD, 12));
        PiePlot plot = (PiePlot) jFreeChart.getPlot();
        // 设置饼状图体里的的各个标签字体
        plot.setLabelFont(new Font("微软雅黑", Font.BOLD, 12));
        // 设置图表下方的图例说明字体
        jFreeChart.getLegend().setItemFont(new Font("微软雅黑", Font.BOLD, 12));

        // 获取到要保存的路径
        String realPath = ServletActionContext.getRequest().getRealPath("img");
        // 保存图片到路径
        FileOutputStream fos = new FileOutputStream(realPath + "/test.jpg");
        ChartUtilities.writeChartAsJPEG(fos, 1, jFreeChart, 400, 300, null);
        fos.close();
        return SUCCESS;
    }

    public PieService getPieService() {
        return pieService;
    }

    public void setPieService(PieService pieService) {
        this.pieService = pieService;
    }

    public JFreeChart getjFreeChart() {
        return jFreeChart;
    }

    public void setjFreeChart(JFreeChart jFreeChart) {
        this.jFreeChart = jFreeChart;
    }

}

2.jsp页面

<body>
    <img alt="图表" src="${pageContext.request.contextPath}/img/test.jpg">
</body>

 

posted on 2016-12-08 10:59  cnsdhzzl  阅读(395)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3