2014-04-30 21 views
1

我正在使用DynamicTimeSeriesCollection將測量值從串行端口繪製到我的圖中。 我想使用我在其他帖子中找到的代碼。DynamicTimeSeriesCollection和串行通信

我要實現的是這樣的:從另一個職位 Using JFreeChart to display recent changes in a time series

代碼,我發現:

How to combine Java plot code and Java serial code to read Arduino sensor value?

1. Move dataset and newData up to become instance variables: 

DynamicTimeSeriesCollection dataset; 
float[] newData = new float[1]; 

2. Add a method that appends your data to the chart's dataset: 

public synchronized void addData(byte[] chunk) { 
    for (int i = 0; i < chunk.length; i++) { 
     newData[0] = chunk[i]; 
     dataset.advanceTime(); 
     dataset.appendData(newData); 
    } 
} 

3. Invoke the method from serialEvent(): 

demo.addChunk(chunk); 

這裏是SerialCommunication類中我的序列事件方法:

public void serialEvent(SerialPortEvent oEvent) { 
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { 
     try 
     { 
      Date d = new Date(); 
      SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
      String datetime = dt.format(d); 
      String inputLine = input.readLine(); 

      String[] measurements = inputLine.split(","); 
      double humidity = Double.parseDouble(measurements[0]); 
      double temp = Double.parseDouble(measurements[1]); 
      double ldr = Double.parseDouble(measurements[2]); 
      humidityList.add(humidity); 
      tempList.add(temp); 
      ldrList.add(ldr); 

      System.out.println(datetime+" > "+inputLine); 
     } 
     catch (Exception e) { 
      System.err.println(e.toString()); 
     } 
    } 
} 

和ArrayList的串口通信類:

private ArrayList<Double> humidityList = new ArrayList<Double>(); 
private ArrayList<Double> tempList = new ArrayList<Double>(); 
private ArrayList<Double> ldrList = new ArrayList<Double>(); 

這裏是我怎麼沒在GUI類中聲明的ArrayList:

private static ArrayList<Double> m1; 
private static ArrayList<Double> m2; 
private static ArrayList<Double> m3; 


public GUI(final String title,ArrayList<Double> humidity,ArrayList<Double> temp,ArrayList<Double> ldr) 
{ 

super(title); 
m1 = humidity; 
m2 = temp; 
m3 = ldr; 

我也嘗試修改了我與我的測量,但沒有運氣找到代碼。任何想法我怎麼能做到這一點?

回答

1

SwingWorker是處理此問題的最佳方法。

  • 創建一個類Measurement包含三個Double屬性。

  • 擴展SwingWorker<Measurement, Measurement>

  • 在你執行doInBackground()publish()每個Measurement,因爲它到達。

  • 在實施process()時,更新圖表的數據集,如建議herehere