Dynamic Data Example
Shows how to use the WebGraph library to display realtime, streaming data.
This example shows how to create a custom subclass of DataSource to represent dynamic data, data that changes over time.
back to index
The source code:
|
/**
* @version $Id: DynamicDataExample.java,v 1.2 2000/11/13 18:47:16 Administrator Exp $
*/
import java.applet.*;
import java.awt.*;
import com.smartmoney.webgraph.*;
public class DynamicDataExample
extends Applet
{
public void init()
{
ParameterParser parser = new ParameterParser(this);
NumericGraph graph = new NumericGraph();
DynamicDataSource dataSource = new DynamicDataSource();
GraphModel model = new GraphModel(dataSource);
GraphElement line = new LineElement(model);
line.setColor(Color.green.darker());
line.setShowCallout(false);
graph.addGraphElement(line);
graph.setGraphMinimum(-1.2);
graph.setGraphMaximum(1.2);
graph.setDrawXValue(false);
graph.setDrawXLabels(false);
GraphParameterParser.parse(graph, parser);
setLayout(new BorderLayout());
add(graph, BorderLayout.CENTER);
dataSource.start();
}
}
class DynamicDataSource
extends DataSource
implements Runnable
{
static final int ARRAY_SIZE = 300;
private DataSet currentData;
private Thread thread;
private double factor;
public int size()
{
return ARRAY_SIZE;
}
synchronized public DataSet getData()
{
if (currentData == null) fillData();
return currentData;
}
public int getNormalIndex()
{
return 0;
}
public int getType()
{
return TDOUBLE;
}
synchronized private void fillData()
{
if (currentData == null)
{
currentData = new DataSet();
currentData.xValues = new GraphableDouble[300];
for (int i = 0; i < ARRAY_SIZE; i++)
currentData.xValues[i] = new GraphableDouble(i);
currentData.yValues = new double[][]{new double[ARRAY_SIZE]};
}
for (int i = 0; i < ARRAY_SIZE; i++)
currentData.yValues[0][i]
//= (.8 + (.4 * Math.random())) *
= Math.sin(factor) * Math.sin(2 * Math.PI * i / ARRAY_SIZE);
factor += Math.PI / 17;
if (factor >= 2 * Math.PI) factor = 0;
}
public void start()
{
if (thread != null)
thread.stop();
thread = new Thread(this);
thread.start();
}
public void run()
{
factor = 0;
while (Thread.currentThread() == thread)
{
try
{
Thread.sleep(33);
} catch (InterruptedException e)
{
}
fillData();
updateListeners();
}
}
}
Copyright (c) 2006 SmartMoney.com
|