JFreeChart实现实时曲线图
最近要用到实时曲线图,在网上大概找了一下,有两种实现方式,一种就是JFreeChart的官方实例MemoryUsageDemo.java.通过一个实现java.Swing.Timer的内部类,在其监听器中将实时数据添加进TimeSeries,由于Timer是会实时执行的,所以这个方法倒是没有什么问题,可以参考代码。
另一种方式就是将实时类实现Runnable接口,在其run()方法中,通过无限循环将实时数据添加进TimeSeries,下面是较简单的实现代码:
//RealTimeChart.java
importorg.jfree.chart.ChartFactory;
importorg.jfree.chart.ChartPanel;
importorg.jfree.chart.JFreeChart;
importorg.jfree.chart.axis.ValueAxis;
importorg.jfree.chart.plot.XYPlot;
importorg.jfree.data.time.Millisecond;
importorg.jfree.data.time.TimeSeries;
importorg.jfree.data.time.TimeSeriesCollection;
publicclassRealTimeChartextendsChartPanelimplementsRunnable
{
privatestaticTimeSeriestimeSeries;
privatelongvalue=0;
publicRealTimeChart(StringchartContent,Stringtitle,StringyaxisName)
{
super(createChart(chartContent,title,yaxisName));
}
privatestaticJFreeChartcreateChart(StringchartContent,Stringtitle,StringyaxisName){
//创建时序图对象
timeSeries=newTimeSeries(chartContent,Millisecond.class);
TimeSeriesCollectiontimeseriescollection=newTimeSeriesCollection(timeSeries);
JFreeChartjfreechart=ChartFactory.createTimeSeriesChart(title,"时间(秒)",yaxisName,timeseriescollection,true,true,false);
XYPlotxyplot=jfreechart.getXYPlot();
//纵坐标设定
ValueAxisvalueaxis=xyplot.getDomainAxis();
//自动设置数据轴数据范围
valueaxis.setAutoRange(true);
//数据轴固定数据范围30s
valueaxis.setFixedAutoRange(30000D);
valueaxis=xyplot.getRangeAxis();
//valueaxis.setRange(0.0D,200D);
returnjfreechart;
}
publicvoidrun()
{
while(true)
{
try
{
timeSeries.add(newMillisecond(),randomNum());
Thread.sleep(300);
}
catch(InterruptedExceptione){}
}
}
privatelongrandomNum()
{
System.out.println((Math.random()*20+80));
return(long)(Math.random()*20+80);
}
}
//Test.java
importjava.awt.BorderLayout;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjavax.swing.JFrame;
publicclassTest
{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args)
{
JFrameframe=newJFrame("TestChart");
RealTimeChartrtcp=newRealTimeChart("RandomData","随机数","数值");
frame.getContentPane().add(rtcp,newBorderLayout().CENTER);
frame.pack();
frame.setVisible(true);
(newThread(rtcp)).start();
frame.addWindowListener(newWindowAdapter()
{
publicvoidwindowClosing(WindowEventwindowevent)
{
System.exit(0);
}
});
}
}
这两中方法都有一个问题,就是每实现一个图就要重新写一次,因为实时数据无法通过参数传进来,在想有没有可能通过setXXX()方式传进实时数据,那样的话就可以将实时曲线绘制类封装起来,而只需传递些参数即可,或者谁有更好的办法?
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。