基于此example,我想每10秒更新一次时间序列图表。但是,如果我使用swing Timer
每10秒更新一次图表,则在图表上显示它仅在1秒内自行更新,即使经过的时间是10秒。这是我的变体,它基本上每10秒从一个在线数据库的位置获取最新温度,并(尝试)在图表上绘制它:
/** @see https://stackoverflow.com/questions/5048852 */
public class l extends ApplicationFrame {
TestWeatherTimeLapseService getTemp = new TestWeatherTimeLapseService(); //gets temperature
private static final String TITLE = "Dynamic Series";
private static final int COUNT = 1 ;
private static final int DELAY = 10000;
private Timer timer;
public l(final String title) {
super(title);
final DynamicTimeSeriesCollection dataset =
new DynamicTimeSeriesCollection(1,60, new Second());
Date date = new Date();
dataset.setTimeBase(new Second(date));
dataset.addSeries(gaussianData(), 0, "Gaussian data");
JFreeChart chart = createChart(dataset);
this.add(new ChartPanel(chart), BorderLayout.CENTER);
timer = new Timer(DELAY, new ActionListener() {
float[] newData = new float[1];
@Override
public void actionPerformed(ActionEvent e) {
newData[0] = randomValue();
dataset.advanceTime();
dataset.appendData(newData);
}
});
}
private float randomValue() {
String currTemperature="";
try {
currTemperature=getTemp.getWeatherData("Laverton")[1]; //get temperature of laverton
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
float number = Float.parseFloat(currTemperature);
number=(float) (number-273.15);
return number;
}
private float[] gaussianData() {
float[] a = new float[COUNT];
a[0] = randomValue();
return a;
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
TITLE, "time", "milliVolts", dataset, true, true, false);
final XYPlot plot = result.getXYPlot();
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange(true);
ValueAxis range = plot.getRangeAxis();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setTickUnit(new DateTickUnit(DateTickUnitType.SECOND, 5));
axis.setDateFormatOverride(new SimpleDateFormat("mm:ss"));
range.setRange(-10,50);
return result;
}
public void start() {
timer.start();
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
l demo = new l(TITLE);
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
// Run some code;
demo.start();
}
});
}}
答案 0 :(得分:1)
您的DynamicTimeSeriesCollection
构造函数指定了60个时刻,每个时间为Second
个advanceTime()
。结果,每次调用advanceTime()
都会将时间移动一秒钟。一种方法是调用@Override
public void actionPerformed(ActionEvent e) {
newData[0] = randomValue();
for (int i = 0; i < 10; i++) {
dataset.advanceTime();
dataset.appendData(newData);
}
}
以匹配您的下一个阅读。从原始example开始,以下更改会产生10秒间隔显示的效果:
setTimeBase()
另请参阅gaussianData()
关于系列初始化的相关discussion。例如,COUNT
的此实现在第一个private float[] gaussianData() {
float[] a = new float[COUNT];
for (int i = 0; i < a.length; i++) {
if (i % 10 == 0) a[i] = randomValue();
}
return a;
}
秒内每10秒更改一次数据。
{{1}}