SSH框架通过JFreeChart实现柱状图和获取项目路径

获取项目路径:String url= ServletActionContext.getRequest().getRealPath("/upload");

一.直接生成的图片输出到jsp页面

1.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>Insert title here</title>
</head>
<body>
 <!--img src='D:\temp\chart.jpg' width="680" height="700" οnlοad="alert('图片存在');"  οnerrοr="alert('无此图片');"/-->
 <img alt="统计图" src="<%=basePath%>/chart2.action">   
</body>
</html>

2.action类

	public String execute() throws Exception{
	 //添加数据
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();
			dataset.addValue(42000, "月份" , "1月");
			dataset.addValue(40000 , "月份" , "2月");
			dataset.addValue(34000 , "月份" , "3月");
			dataset.addValue(18000 , "月份" , "4月");
			dataset.addValue(26000 , "月份" , "5月");
			dataset.addValue(42000 , "月份" , "6月");
			dataset.addValue(40000 , "月份" , "7月");
			dataset.addValue(34000 , "月份" , "8月");
			dataset.addValue(18000 , "月份" , "9月");
			dataset.addValue(26000 , "月份" , "10月");
			dataset.addValue(45000 , "月份" , "11月");
			dataset.addValue(38000 , "月份" , "12月");
			
			//创建一个柱状图
			JFreeChart chart = ChartFactory.createBarChart3D("年度人口统计图", "人口", "数量",dataset,PlotOrientation.VERTICAL, true, false, false);
			chart.setTitle(new TextTitle("年度人口统计图", new Font("黑体", Font.ITALIC,22)));
			LegendTitle legend = chart.getLegend(0);
			legend.setItemFont(new Font("宋体", Font.BOLD, 14));
			CategoryPlot plot = (CategoryPlot) chart.getPlot();
			CategoryAxis categoryAxis = plot.getDomainAxis();
			categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 22));
			categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
			categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 18));
			NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
			numberAxis.setLabelFont(new Font("宋体", Font.BOLD, 22));
	
			HttpServletResponse response=ServletActionContext.getResponse();
			response.setContentType("image/");
			ChartUtilities.writeChartAsJPEG(response.getOutputStream(), 1, chart, 900, 600, null);
			response.getOutputStream().close();
			
			return null;
	}
	
3.struts.xml配置

      <action name="chart2" class="Char2tAction">
      <result name="success">/Chart.jsp</result>
      </action>

4.效果图



二.生成图片保存到本地:

1.生成图片

	public void createChart() {
		// TODO Auto-generated method stub		
		DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 
		dataset.addValue(1001, "1", "A");	
		dataset.addValue(800, "2", "A");		
		dataset.addValue(150, "3", "A");	
		dataset.addValue(150, "1", "B");
		dataset.addValue(150, "2", "B");	
		dataset.addValue(250, "3", "B");	
		dataset.addValue(150, "1", "C");	
		dataset.addValue(33, "2", "C");	
		dataset.addValue(900, "3", "C");	
//		JFreeChart chart = ChartFactory.createBarChart3D( 
//											"", // 图表标题 
//											"", // 目录轴的显示标签 
//											"产量", // 数值轴的显示标签 
//											dataset, // 数据集 
//											PlotOrientation.VERTICAL , // 图表方向:垂直 
//											true, // 是否显示图例(对于简单的柱状图必须是false) 
//											false, // 是否生成工具 
//											false // 是否生成URL链接 
//									); 
		//JFreeChart chart = ChartFactory.createBarChart3D("","","产量",dataset,PlotOrientation.VERTICAL,true,false,false);
		JFreeChart chart = ChartFactory.createBarChart3D("销量统计图", "种类", "产量", dataset, PlotOrientation.VERTICAL, true, false, false);
				
		//重新设置图标标题,改变字体 
		chart.setTitle(new TextTitle("销量统计图", new Font("黑体", Font.ITALIC , 22))); 
				//取得统计图标的第一个图例 
				LegendTitle legend = chart.getLegend(0); 
				//修改图例的字体 
		        legend.setItemFont(new Font("宋体", Font.BOLD, 14)); 
				//legend.setItemFont(new Font("宋体", Font.TRUETYPE_FONT, 14)); 
				CategoryPlot plot = (CategoryPlot)chart.getPlot(); 
				
				chart.setBackgroundPaint(ChartColor.WHITE); 

				//设置柱状图到图片上端的距离
				ValueAxis rangeAxis = plot.getRangeAxis();
				rangeAxis.setUpperMargin(0.5);
				
				//取得横轴 
				CategoryAxis categoryAxis = plot.getDomainAxis(); 
				//设置横轴显示标签的字体 
				categoryAxis.setLabelFont(new Font("宋体" , Font.BOLD , 22)); 
				//分类标签以45度角倾斜 
//				categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); 
				categoryAxis.setTickLabelFont(new Font("宋体" , Font.BOLD , 18)); 
				
				//取得纵轴 
				NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis(); 
				//设置纵轴显示标签的字体 
				numberAxis.setLabelFont(new Font("宋体" , Font.BOLD , 22)); 

				//在柱体的上面显示数据
				BarRenderer custombarrenderer3d = new BarRenderer();
				custombarrenderer3d.setBaseItemLabelPaint(Color.BLACK);//数据字体的颜色
				custombarrenderer3d.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
				custombarrenderer3d.setBaseItemLabelsVisible(true);
				plot.setRenderer(custombarrenderer3d);
                //HttpServletRequest request = null;
				//request.getSession().getServletContext().getRealPath("/");
				//URL a = Thread.currentThread().getContextClassLoader().getResource("");
                //URL a = Thread.currentThread().getContextClassLoader().getResource("");     
                //System.out.println(a);
				FileOutputStream fos = null;  
				//String imagePath = "D:\\chart.jpg";
				String imagePath = "D:\\temp\\chart.jpg";
				ChartRenderingInfo info = new ChartRenderingInfo(); 
				try {
					fos = new FileOutputStream(imagePath);
					//将统计图标输出成JPG文件 
					ChartUtilities.writeChartAsJPEG( 
						fos, //输出到哪个输出流 
						1, //JPEG图片的质量,0~1之间 
						chart, //统计图标对象 
						800, //宽 
						600,//高
						info //ChartRenderingInfo 信息 
					);
					fos.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					
					e.printStackTrace();
				}
		
	}

2.显示到jsp:     

		try{
			
			String impath = "D:\\temp\\chart.jpg";//此处的图路径,是上面所示代码中生成柱状图的存储路径
			File file = new File(impath);
				
			InputStream inputStream = null;
			if(file.exists()){
				try {
					inputStream = new FileInputStream(file);
							
				} catch (FileNotFoundException e) {
						
				}
			}

			int i = inputStream.available(); 
		         byte data[] = new byte[i];
		         inputStream.read(data);
		            
		         HttpServletResponse response = ServletActionContext.getResponse();
		         ServletOutputStream out = response.getOutputStream();
		            
		         response.setContentType("image/jpeg");
		            
		         out.write(data); 
		         out.flush();      
		         out.close(); 
		            
		}catch(IOException e){
		         e.printStackTrace(); 
		}
















  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要使用JFreeChart生成柱状图,需要进行以下步骤: 1. 创建一个数据集对象,用于存储需要绘制的数据 2. 创建一个图表对象,并设置标题、x轴和y轴标签 3. 创建一个柱状图渲染器对象,设置颜色、边框等属性 4. 将数据集对象和渲染器对象关联到图表对象中 5. 将图表对象绘制到Swing组件中,如JPanel或JFrame中 下面是一个示例代码,可以生成一个简单的柱状图: ```java import java.awt.Color; import java.awt.Dimension; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.data.category.DefaultCategoryDataset; public class BarChartExample { public static void main(String[] args) { // 生成随机数据 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Random random = new Random(); for (int i = 0; i < 5; i++) { dataset.addValue(random.nextInt(100), "Series 1", "Category " + i); } // 创建柱状图对象 JFreeChart chart = ChartFactory.createBarChart( "Bar Chart Example", // 图表标题 "Category", // x轴标签 "Value", // y轴标签 dataset, // 数据集 PlotOrientation.VERTICAL, // 图表方向 true, // 是否显示图例 true, // 是否生成工具提示 false // 是否生成URL链接 ); // 设置柱状图渲染器 CategoryPlot plot = (CategoryPlot) chart.getPlot(); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setSeriesPaint(0, Color.BLUE); renderer.setDrawBarOutline(false); // 设置x轴标签位置 CategoryAxis xAxis = plot.getDomainAxis(); xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 设置y轴范围 NumberAxis yAxis = (NumberAxis) plot.getRangeAxis(); yAxis.setRange(0, 100); // 将图表绘制到Swing组件中 JPanel panel = new ChartPanel(chart); panel.setPreferredSize(new Dimension(500, 300)); JFrame frame = new JFrame("Bar Chart Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } } ``` 运行以上代码,即可看到生成的柱状图
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值