JFreeChart实现实时曲线图
程序员文章站
2023-12-21 13:44:34
最近要用到实时曲线图,在网上大概找了一下,有两种实现方式,一种就是jfreechart的官方实例memoryusagedemo.java.通过一个实现java.swing....
最近要用到实时曲线图,在网上大概找了一下,有两种实现方式,一种就是jfreechart的官方实例memoryusagedemo.java.通过一个实现java.swing.timer的内部类,在其监听器中将实时数据添加进timeseries,由于timer是会实时执行的,所以这个方法倒是没有什么问题,可以参考代码。
另一种方式就是将实时类实现runnable接口,在其run()方法中,通过无限循环将实时数据添加进timeseries,下面是较简单的实现代码:
//realtimechart .java import org.jfree.chart.chartfactory; import org.jfree.chart.chartpanel; import org.jfree.chart.jfreechart; import org.jfree.chart.axis.valueaxis; import org.jfree.chart.plot.xyplot; import org.jfree.data.time.millisecond; import org.jfree.data.time.timeseries; import org.jfree.data.time.timeseriescollection; public class realtimechart extends chartpanel implements runnable { private static timeseries timeseries; private long value=0; public realtimechart(string chartcontent,string title,string yaxisname) { super(createchart(chartcontent,title,yaxisname)); } private static jfreechart createchart(string chartcontent,string title,string yaxisname){ //创建时序图对象 timeseries = new timeseries(chartcontent,millisecond.class); timeseriescollection timeseriescollection = new timeseriescollection(timeseries); jfreechart jfreechart = chartfactory.createtimeserieschart(title,"时间(秒)",yaxisname,timeseriescollection,true,true,false); xyplot xyplot = jfreechart.getxyplot(); //纵坐标设定 valueaxis valueaxis = xyplot.getdomainaxis(); //自动设置数据轴数据范围 valueaxis.setautorange(true); //数据轴固定数据范围 30s valueaxis.setfixedautorange(30000d); valueaxis = xyplot.getrangeaxis(); //valueaxis.setrange(0.0d,200d); return jfreechart; } public void run() { while(true) { try { timeseries.add(new millisecond(), randomnum()); thread.sleep(300); } catch (interruptedexception e) { } } } private long randomnum() { system.out.println((math.random()*20+80)); return (long)(math.random()*20+80); } } //test.java import java.awt.borderlayout; import java.awt.event.windowadapter; import java.awt.event.windowevent; import javax.swing.jframe; public class test { /** * @param args */ public static void main(string[] args) { jframe frame=new jframe("test chart"); realtimechart rtcp=new realtimechart("random data","随机数","数值"); frame.getcontentpane().add(rtcp,new borderlayout().center); frame.pack(); frame.setvisible(true); (new thread(rtcp)).start(); frame.addwindowlistener(new windowadapter() { public void windowclosing(windowevent windowevent) { system.exit(0); } }); } }
这两中方法都有一个问题,就是每实现一个图就要重新写一次,因为实时数据无法通过参数传进来,在想有没有可能通过setxxx()方式传进实时数据,那样的话就可以将实时曲线绘制类封装起来,而只需传递些参数即可,或者谁有更好的办法?
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。