JFreeChart实现实时曲线图
最 近要用到实时曲线图,在网上大概找了一下,有两种实现方式,一种就是JFreeChart的官方实例MemoryUsageDemo.java.通过一个 实现java.Swing.Timer的内部类,在其监听器中将实时数据添加进TimeSeries,由于Timer是会实时执行的,所以这个方法倒是没 有什么问题,可以参考代码。
另一种方式就是将实时类实现Runnable接口,在其run()方法中,通过无限循环将实时数据添加进TimeSeries,下面是较简单的实现代码:
java 代码
- //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()方式传进实时数据,那样的话就可以将实时曲线绘制类封装起来,而只需传递些参数即可(或者谁有更好的办法??)。
Copy:
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!