I've made a live graph using JFreeChart where it shows the temperature for a location every 10 seconds. However on the x-axis, it shows seconds instead of the current time (like 19:45 for example) for each temperature. How would I achieve showing the current time on the x-axis?
Here's my code based this example:
public class DynamicTimeSeriesChart extends JPanel {
TestWeatherTimeLapseService getTemp = new TestWeatherTimeLapseService(); //gets temperature
private final DynamicTimeSeriesCollection dataset;
private final JFreeChart chart;
public DynamicTimeSeriesChart(final String title) {
dataset = new DynamicTimeSeriesCollection(1, 10000, new Second());
Date date = new Date();
dataset.setTimeBase(new Second(date));
dataset.addSeries(new float[1], 0, title);
chart = ChartFactory.createTimeSeriesChart(
title, "Time", title, dataset, true, true, false);
final XYPlot plot = chart.getXYPlot();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setFixedAutoRange(10000);
axis.setDateFormatOverride(new SimpleDateFormat("ss.SS"));
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setMouseWheelEnabled(true);
add(chartPanel);
chart.getXYPlot().setDomainPannable(true);
}
public void update() {
float[] newData = new float[1];
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);
dataset.advanceTime();
newData[0] = number;
dataset.appendData(newData);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DynamicTimeSeriesChart chart
= new DynamicTimeSeriesChart("Temperature");
frame.add(chart);
frame.pack();
Timer timer = new Timer(10000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chart.update();
}
});
timer.start();
frame.setVisible(true);
}
});
}}
You've given your DateAxis
a SimpleDateFormat
override of "ss.SS"
, which shows seconds.milliseconds
. You might want hour:minutes:seconds
:
axis.setDateFormatOverride(new SimpleDateFormat("HH:mm.ss"));