Java读取数据库数据生成柱状图

来源:互联网 发布:家装招标软件 编辑:程序博客网 时间:2024/05/23 14:30
此案例是用swing显示数据的。需要引入jfreechart相关包,不同版本可能包不相同,本人用的是
此案例在ssi框架下会报错,不用框架就没问题。
Java后台逻辑代码:
public class BarChart {ChartPanel frame1;public BarChart() {CategoryDataset dataset = getDataSet();JFreeChart chart = ChartFactory.createBarChart3D("水果", // 图表标题"水果种类", // 目录轴的显示标签"数量", // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成URL链接);// 从这里开始CategoryPlot plot = chart.getCategoryPlot();// 获取图表区域对象CategoryAxis domainAxis = plot.getDomainAxis(); // 水平底部列表domainAxis.setLabelFont(new Font("黑体", Font.BOLD, 14)); // 水平底部标题domainAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 12)); // 垂直标题ValueAxis rangeAxis = plot.getRangeAxis();// 获取柱状rangeAxis.setLabelFont(new Font("黑体", Font.BOLD, 15));chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));chart.getTitle().setFont(new Font("宋体", Font.BOLD, 20));// 设置标题字体// 到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题frame1 = new ChartPanel(chart, true); // 这里也可以用chartFrame,可以直接生成一个独立的Frame}private static CategoryDataset getDataSet() {DefaultCategoryDataset dataset = new DefaultCategoryDataset();List<News> data = new ArrayList<News>();NewsDao dao = new NewsDao();ArrayList<News> list = dao.queryAll();double value =0;String rowKeys=null;String columnKeys=null;for (News news : list) {//data.add(new News(news.getNewsId(), news.getTypeId(), news//.getTitle(), news.getPublishTime(), news.getBody(), news//.getTag(), news.getAuthor(), news.getClicks(), news//.getImgUrl()));value = news.getNewsId();rowKeys = news.getTitle();columnKeys =  news.getAuthor();dataset.addValue(value, rowKeys, columnKeys);System.out.println(value+"  "+rowKeys+"  "+columnKeys);}//if(value!=0&&rowKeys!=null&&columnKeys!=null){//System.out.println(value+"  "+rowKeys+"  "+columnKeys);//dataset.addValue(value, rowKeys, columnKeys);//}//dataset.addValue(100, "北京", "苹果");//dataset.addValue(100, "上海", "苹果");//dataset.addValue(100, "广州", "苹果");//dataset.addValue(200, "北京", "梨子");//dataset.addValue(200, "上海", "梨子");//dataset.addValue(200, "广州", "梨子");//dataset.addValue(300, "北京", "葡萄");//dataset.addValue(300, "上海", "葡萄");//dataset.addValue(300, "广州", "葡萄");//dataset.addValue(400, "北京", "香蕉");//dataset.addValue(400, "上海", "香蕉");//dataset.addValue(400, "广州", "香蕉");//dataset.addValue(500, "北京", "荔枝");//dataset.addValue(500, "上海", "荔枝");//dataset.addValue(500, "广州", "荔枝");return dataset;}public ChartPanel getChartPanel() {return frame1;}public static void main(String[] args) {JFrame frame = new JFrame("Java数据统计图");// frame.setLayout(new GridLayout(2,2,10,10));frame.add(new BarChart().getChartPanel()); // 添加柱形图// frame.add(new BarChart1().getChartPanel()); //添加柱形图的另一种效果// frame.add(new PieChart().getChartPanel()); //添加饼状图// frame.add(new TimeSeriesChart().getChartPanel()); //添加折线图frame.setBounds(50, 50, 800, 600);frame.setVisible(true);}}
其他类就不上代码了,跟你平时连数据库一样。
看张效果图:[数据乱写的]
0 0
原创粉丝点击