JSP页面中嵌入动态图表的两种方法 :在JSP页面中插入Applet小程序 通过JavaBean动态生成图像。
JSP是一种广泛应用的网页设计技术 ,它是一种HTML和Java脚本混合的编程技术 ,它结合了HTML的静态特性和Java语言的动态能力 ,因此用它进行动态网页设计非常方便。在进行图像处理时 ,一般处理静态图片非常容易 ,但是 ,在实际应用中常常需要动态地在网页中生成二维的图形.
基于JFreeChart开发的一个时序图的绘制。代码如下:
实例中createDataset()方法用于创建数据集合对象。时序图的数据集合与其他数据集合不同,它需要添加一个时间段内的所有数据,通常采用TimeSeries类进行添加。该实例中通过Math类的random()方法进行随机生成。
import java.awt.*
import java.awt.event.ActionEvent
import
java.awt.event.ActionListener
import java.io.BufferedInputStream
import
java.io.DataInputStream
import java.io.FileOutputStream
import
java.io.IOException
import java.net.URL
import
java.net.URLConnection
import java.text.DateFormat
import
java.text.ParseException
import java.text.SimpleDateFormat
import
java.util.Calendar
import java.util.Date
import java.util.Random
import javax.swing.JApplet
import javax.swing.Timer
import org.jfree.chart.*
import
org.jfree.chart.annotations.CategoryTextAnnotation
import
org.jfree.chart.axis.CategoryAnchor
import
org.jfree.chart.axis.CategoryAxis
import
org.jfree.chart.axis.CategoryLabelPositions
import
org.jfree.chart.axis.DateAxis
import
org.jfree.chart.axis.DateTickUnit
import
org.jfree.chart.axis.DateTickUnitType
import
org.jfree.chart.axis.ValueAxis
import
org.jfree.chart.labels.StandardCategoryItemLabelGenerator
import
org.jfree.chart.plot.CategoryPlot
import
org.jfree.chart.plot.PlotOrientation
import
org.jfree.chart.plot.XYPlot
import
org.jfree.chart.renderer.category.BarRenderer
import
org.jfree.chart.title.TextTitle
import
org.jfree.data.category.CategoryDataset
import
org.jfree.data.category.IntervalCategoryDataset
import org.jfree.chart.axis.NumberAxis
import
org.jfree.data.category.DefaultCategoryDataset
import
org.jfree.data.gantt.Task
import org.jfree.data.gantt.TaskSeries
import
org.jfree.data.gantt.TaskSeriesCollection
import
org.jfree.data.time.Day
import org.jfree.data.time.Second
import
org.jfree.data.time.TimeSeries
import
org.jfree.data.time.TimeSeriesCollection
import
org.jfree.data.xy.XYDataset
public class shixutu extends JApplet {
//PLOT_FONT是一静态的字体常量对象,使用此对象可以避免反复用到的字体对象被多次创建
private static final Font PLOT_FONT = new Font("黑体", Font.ITALIC ,
18)
JFreeChart chart
//创建数据动态更新的监听
class DataGenerator extends Timer
implements ActionListener {
private static final long serialVersionUID =
3977867288743720504L
String
equID
//设备ID号
int
totalTask
//任务数
String[][]
strTask
//任务情况
public void
actionPerformed(ActionEvent actionevent) {
addTotalObservation()
} DataGenerator()
{
super(1000,
null)
addActionListener(this)
System.out.println("super")
}
}
//将更新的数据添加到chart中
private void addTotalObservation()
{
System.out.println("addTotalObservation")
//设置新的数据集
chart.getXYPlot().setDataset(createDataset())
//通知Jfreechart
数据发生了改变,重新绘制柱状图
if
(chart != null)
{
chart.fireChartChanged()
}
}
private static void
processChart(JFreeChart chart)
{
//设置标题字体
chart.getTitle().setFont(new Font("隶书", Font.BOLD,
26))
//设置背景色
chart.setBackgroundPaint(new
Color(252,175,134))
XYPlot plot = chart.getXYPlot()
//获取图表的绘制属性
plot.setDomainGridlinesVisible(false)
//设置网格不显示
//获取时间轴对象
DateAxis dateAxis = (DateAxis)
plot.getDomainAxis()
dateAxis.setLabelFont(PLOT_FONT)
//设置时间轴字体
//设置时间轴标尺值字体
dateAxis.setTickLabelFont(new
Font("宋体",Font.PLAIN,12))
dateAxis.setLowerMargin(0.0)
//设置时间轴上显示的最小值
//获取数据轴对象
ValueAxis valueAxis =
plot.getRangeAxis()
valueAxis.setLabelFont(PLOT_FONT)
//设置数据字体
DateFormat format = new SimpleDateFormat("mm分ss秒")
//创建日期格式对象
//创建DateTickUnit对象
DateTickUnit dtu = new
DateTickUnit(DateTickUnitType.SECOND,30,format)
dateAxis.setTickUnit(dtu)
//设置日期轴的日期标签 } //将结果输出在文件中
private static
void writeChartAsImage(JFreeChart chart)
{
FileOutputStream fos_jpg =
null
try
{
fos_jpg = new
FileOutputStream("D:\\test\\shixutu.jpg")
ChartUtilities.writeChartAsJPEG(fos_jpg, 1, chart, 400, 300,
null)
} catch (Exception e)
{
e.printStackTrace()
} finally
{
try
{
fos_jpg.close()
} catch (Exception e)
{
}
}
}
//创建数据集合对象
public static XYDataset createDataset()
{
//实例化TimeSeries对象
TimeSeries timeseries = new
TimeSeries("Data")
Second second = new Second()
//实例化Day
double d =
50D
//添加一年365天的数据
for (int i = 0i <500i++)
{
d = d + (Math.random() - 0.5) * 10
//创建随机数据
timeseries.second(day, d)
//向数据集合中添加数据
second = (Second)
second.next()
}
TimeSeriesCollection timeSeriesCollection =
new
TimeSeriesCollection(timeseries)
//返回数据集合对象
return timeSeriesCollection } //Applet程序初始化
public void init()
{
// 1.
得到数据
XYDataset dataset =
createDataset()
// 2.
构造chart
chart =
ChartFactory.createTimeSeriesChart(
"时序图示范", //
图表标题
"时间", //
目录轴的显示标签--横轴
"数值", //
数值轴的显示标签--纵轴
dataset, //
数据集
false,
false, //
是否生成工具
false //
是否生成URL链接
)
// 3.
处理chart中文显示问题
processChart(chart)
// 4.
chart输出图片
//writeChartAsImage(chart)
// 5. chart
以swing形式输出
//6.使用applet输出
ChartPanel chartPanel = new
ChartPanel(chart)
chartPanel.setPreferredSize(new
java.awt.Dimension(800,500))
getContentPane().add(chartPanel) (new
DataGenerator()).start()
}
public void
paint(Graphics g)
{
if
(chart != null)
{
chart.draw((Graphics2D) g,
getBounds())
}
}
public void destroy() {
}
}
简单的可以用java.awt.geom java.awt.image 这两个包// 清空缓冲区
response.reset()
// 注意这里的MIME类型
response.setContentType("image/png")
// 创建一个 610X400 的图像
int width = 610, height = 400
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB)
// 创建Java2D对象
/**
Graphics g = image.getGraphics()
Graphics2D g2d = (Graphics2D)g
*/
Graphics2D g2d = image.createGraphics()
// 填充背景
g2d.setColor(Color.WHITE)
g2d.fillRect(0, 0, width, height)
// 绘制新背景
GradientPaint grayGP = new GradientPaint(0, 0, Color.GRAY, width, height,
new Color(200, 200, 200), false)
g2d.setPaint(grayGP)
g2d.fillRoundRect(20, 20, width - 20, height - 20, 50, 50)
g2d.setPaint(Color.WHITE)
g2d.fillRoundRect(12, 12, width - 20, height - 20, 50, 50)
BasicStroke bs = new BasicStroke(4.0f)
g2d.setStroke(bs)
g2d.setPaint(new Color(53, 76, 112))
g2d.drawRoundRect(12, 12, width - 20, height - 20, 50, 50)
GradientPaint blueGP = new GradientPaint(120, 60, new Color(215, 230, 252),
120, 300, Color.WHITE, false)
g2d.setPaint(blueGP)
g2d.fillRect(120, 60, 440, 300)
// 绘制图表标题
String chartTitle = "计算机编程类图书2004年月销售量统计图"
g2d.setFont(new Font("方正粗宋简体", Font.PLAIN, 22))
g2d.setColor(Color.BLACK)
g2d.drawString(chartTitle, 140, 40)
// 创建虚线笔划
float[]dashes = { 3.f }
bs = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
10, dashes, 0)
g2d.setStroke(bs)
g2d.setFont(new Font("Courier New", Font.PLAIN, 12))
String str = "2004-"
int stringLength = 0
for (int i = 1i <= 12i++)
{
// 绘制垂直方向虚线
g2d.drawLine(80+i * 40, 50, 80+i * 40, 360)
// 绘制横轴上月份的说明文字
str += i
stringLength = g2d.getFontMetrics().stringWidth(str)
if (i % 2 == 0)
{
g2d.drawString(str, 80+i * 40 - stringLength / 2, 387)
}
else
{
g2d.drawString(str, 80+i * 40 - stringLength / 2, 375)
}
str = "2004-"
}
str = ""
int stringHeight = 0
for (int i = 0i <300i += 30)
{
// 绘制水平方向虚线
g2d.drawLine(120, 60+i, 570, 60+i)
// 绘制纵轴上销售量的说明文字
str += 100-i / 3
stringHeight = g2d.getFontMetrics().getAscent()
stringLength = g2d.getFontMetrics().stringWidth(str)
g2d.drawString(str, 110-stringLength, 60+i + stringHeight / 2)
str = ""
}
// 绘制坐标轴
g2d.setStroke(new BasicStroke(3.0f))
g2d.setColor(new Color(53, 76, 112))
g2d.drawLine(120, 50, 120, 360)
g2d.drawLine(120, 360, 570, 360)
// 绘制纵坐标上的标题
g2d.setFont(new Font("黑体", Font.PLAIN, 15))
g2d.drawString("月销售量", 40, 45)
// 调用TriangleServlet类,绘制坐标轴上的箭头
TriangleServlet ts = new TriangleServlet()
ts.setFillColor(new Color(53, 76, 112))
ts.setBaseLine(10)
ts.setAlpha(60)
ts.drawTrigangle(570, 360, 2, 2, g2d)// 绘制横坐标轴上的箭头
ts.drawTrigangle(120, 50, 1, 2, g2d)// 绘制纵坐标轴上的箭头
String[] bookTitle = { "JAVA", "C#" }
Color[] bookColor = { Color.RED, Color.ORANGE }
int[] sales = new int[12]
int[] month = new int[12]
g2d.setFont(new Font("Courier New", Font.PLAIN, 12))
for (int i = 0i <bookTitle.lengthi++)
{
// 初始化绘制数据
int bookSales = 0
for (int j = 0j <sales.lengthj++)
{
bookSales = 45+(int)(Math.random() * 50)
sales[j] = 360-bookSales * 3
month[j] = 120+j * 40
}
// 重新设置笔划
g2d.setStroke(new BasicStroke(5.0f))
g2d.setColor(bookColor[i])
// 绘制月销售量折线
g2d.drawPolyline(month, sales, sales.length)
// 绘制图例
g2d.fillRect(30, 140+i * 20, 10, 10)
g2d.setColor(Color.BLACK)
g2d.drawString(bookTitle[i], 45, 150+i * 20)
}
// 部署图形
g2d.dispose()
// 利用ImageIO类的write方法对图像进行编码
ServletOutputStream sos = response.getOutputStream()
ImageIO.write(image, "PNG", sos)
sos.close()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)