Frage

I am using DynamicTimeSeriesCollection to plot measurements from serial port into my graph. I want to use the code that I have found in another post.

I want to achieve something like this: Using JFreeChart to display recent changes in a time series

Code from another post that I have found:

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);

Here is my Serial Event method within SerialCommunication class:

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());
        }
    }
}

And ArrayList in Serial Communication class:

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

Here is how I did declare ArrayList in GUI class:

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;

I did try to modify code that I have found with my measurements but no luck. Any idea how can I achieve this?

War es hilfreich?

Lösung

SwingWorker is the best way to handle this.

  • Create a class Measurement containing three Double attributes.

  • Extend SwingWorker<Measurement, Measurement>

  • In your implementation of doInBackground(), publish() each Measurement as it arrives .

  • In your implementation of process(), update the chart's dataset, as suggested here and here.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top