您好,登錄后才能下訂單哦!
最近要用到實時曲線圖,在網上大概找了一下,有兩種實現方式,一種就是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()方式傳進實時數據,那樣的話就可以將實時曲線繪制類封裝起來,而只需傳遞些參數即可,或者誰有更好的辦法?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。