JFreeChart實現(xiàn)實時曲線圖
最近要用到實時曲線圖,在網(wǎng)上大概找了一下,有兩種實現(xiàn)方式,一種就是JFreeChart的官方實例MemoryUsageDemo.java.通過一個實現(xiàn)java.Swing.Timer的內(nèi)部類,在其監(jiān)聽器中將實時數(shù)據(jù)添加進TimeSeries,由于Timer是會實時執(zhí)行的,所以這個方法倒是沒有什么問題,可以參考代碼。
另一種方式就是將實時類實現(xiàn)Runnable接口,在其run()方法中,通過無限循環(huán)將實時數(shù)據(jù)添加進TimeSeries,下面是較簡單的實現(xiàn)代碼:
//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){
//創(chuàng)建時序圖對象
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();
//縱坐標(biāo)設(shè)定
ValueAxis valueaxis = xyplot.getDomainAxis();
//自動設(shè)置數(shù)據(jù)軸數(shù)據(jù)范圍
valueaxis.setAutoRange(true);
//數(shù)據(jù)軸固定數(shù)據(jù)范圍 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","隨機數(shù)","數(shù)值");
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);
}
});
}
}
這兩中方法都有一個問題,就是每實現(xiàn)一個圖就要重新寫一次,因為實時數(shù)據(jù)無法通過參數(shù)傳進來,在想有沒有可能通過setXXX()方式傳進實時數(shù)據(jù),那樣的話就可以將實時曲線繪制類封裝起來,而只需傳遞些參數(shù)即可,或者誰有更好的辦法?
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
idea2023遠(yuǎn)程調(diào)試springboot的過程詳解
這篇文章主要介紹了idea2023遠(yuǎn)程調(diào)試,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
SpringSecurity如何實現(xiàn)配置單個HttpSecurity
這篇文章主要介紹了SpringSecurity如何實現(xiàn)配置單個HttpSecurity,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08

